Skip to content
Closed
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
13 changes: 13 additions & 0 deletions README_PAPER_TRADING.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
### Local paper trading

The paper-trading commands maintain a local USD-only portfolio and never place real trades:

```bash
colab paper-trading init --balance 1000
colab paper-trading status
colab paper-trading buy --symbol SXBT --quantity 10 --price 0.55
colab paper-trading sell --symbol SXBT --quantity 4 --price 0.60
colab paper-trading recommend --symbol SXBT
```

State: `~/.config/colab-cli/paper-trading.json`. Existing state is reset only after confirmation unless `--force` is supplied.
13 changes: 13 additions & 0 deletions docs/07_paper_trading.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
### Local paper trading

The paper-trading commands maintain a portfolio only on your machine. They never place real trades and never request exchange or brokerage credentials.

```bash
colab paper-trading init --balance 1000
colab paper-trading status
colab paper-trading buy --symbol SXBT --quantity 10 --price 0.55
colab paper-trading sell --symbol SXBT --quantity 4 --price 0.60
colab paper-trading recommend --symbol SXBT
```

State is stored in `~/.config/colab-cli/paper-trading.json`. Use `init --force` to reset the portfolio without a confirmation prompt; interactive `init` asks before resetting existing state. The CLI supports USD only and uses decimal arithmetic for balances and trades.
1 change: 1 addition & 0 deletions docs/README_LINK.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [Local Paper Trading](docs/07_paper_trading.md)
221 changes: 221 additions & 0 deletions src/colab_cli/commands/paper_trading.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
import json
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Optional

import typer
from typing_extensions import Annotated


DEFAULT_BALANCE = Decimal("1000")


def _default_state_path() -> Path:
return Path.home() / ".config" / "colab-cli" / "paper-trading.json"


def _decimal(value: str, name: str) -> Decimal:
try:
result = Decimal(value)
except (InvalidOperation, ValueError):
raise typer.BadParameter(f"{name} must be a valid number")
if not result.is_finite():
raise typer.BadParameter(f"{name} must be finite")
return result


def _load(path: Path) -> dict:
if not path.exists():
raise typer.BadParameter("Paper-trading state is not initialized. Run 'colab paper-trading init'.")
try:
state = json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
raise typer.BadParameter(f"Could not read paper-trading state: {exc}")
if state.get("currency") != "USD":
raise typer.BadParameter("Unsupported persisted currency; only USD is allowed")
return state


def _save(path: Path, state: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(json.dumps(state, indent=2, sort_keys=True) + "\n", encoding="utf-8")
temporary.replace(path)


def _serialize(state: dict) -> dict:
result = dict(state)
result["cash"] = str(state["cash"])
result["positions"] = {
symbol: {
"quantity": str(position["quantity"]),
"average_price": str(position["average_price"]),
}
for symbol, position in state["positions"].items()
}
return result


def _deserialize(raw: dict) -> dict:
raw = dict(raw)
raw["cash"] = Decimal(str(raw["cash"]))
raw["positions"] = {
str(symbol): {
"quantity": Decimal(str(position["quantity"])),
"average_price": Decimal(str(position["average_price"])),
}
for symbol, position in raw.get("positions", {}).items()
}
return raw


def _symbol(value: str) -> str:
symbol = value.strip().upper()
if not symbol or not symbol.replace("-", "").replace("_", "").isalnum():
raise typer.BadParameter("symbol must contain letters, numbers, '-' or '_'")
return symbol


def init(
balance: Annotated[str, typer.Option("--balance", help="Starting USD balance")] = "1000",
force: Annotated[bool, typer.Option("--force", help="Reset without prompting")] = False,
state: Annotated[Optional[str], typer.Option("--state", help="State file override")] = None,
):
"""Initialize or reset the local paper-trading portfolio."""
path = Path(state).expanduser() if state else _default_state_path()
starting_balance = _decimal(balance, "balance")
if starting_balance <= 0:
raise typer.BadParameter("balance must be greater than zero")

if path.exists() and not force:
confirm = typer.confirm("Reset the existing paper-trading portfolio?")
if not confirm:
typer.echo("Initialization cancelled.")
raise typer.Exit(0)

portfolio = {"currency": "USD", "cash": starting_balance, "positions": {}, "trades": []}
_save(path, _serialize(portfolio))
typer.echo(f"Paper-trading portfolio initialized with USD {starting_balance:.2f}")


def status(state: Annotated[Optional[str], typer.Option("--state", help="State file override")] = None):
"""Show local paper-trading cash and positions."""
path = Path(state).expanduser() if state else _default_state_path()
portfolio = _deserialize(_load(path))
typer.echo(f"Cash: USD {portfolio['cash']:.2f}")
if not portfolio["positions"]:
typer.echo("Positions: none")
return
typer.echo("Positions:")
for symbol, position in sorted(portfolio["positions"].items()):
quantity = position["quantity"]
average = position["average_price"]
typer.echo(f" {symbol}: {quantity} shares @ USD {average:.4f} average")


def buy(
symbol: Annotated[str, typer.Option("--symbol")],
quantity: Annotated[str, typer.Option("--quantity")],
price: Annotated[str, typer.Option("--price")],
state: Annotated[Optional[str], typer.Option("--state", help="State file override")] = None,
):
"""Record a local paper buy; no real trade is placed."""
path = Path(state).expanduser() if state else _default_state_path()
portfolio = _deserialize(_load(path))
symbol = _symbol(symbol)
shares = _decimal(quantity, "quantity")
cost = _decimal(price, "price")
if shares <= 0:
raise typer.BadParameter("quantity must be greater than zero")
if cost <= 0:
raise typer.BadParameter("price must be greater than zero")

total = shares * cost
if total > portfolio["cash"]:
typer.echo("Insufficient funds for this paper buy.", err=True)
raise typer.Exit(1)

portfolio["cash"] -= total
existing = portfolio["positions"].get(symbol)
if existing:
old_quantity = existing["quantity"]
old_average = existing["average_price"]
new_quantity = old_quantity + shares
average = ((old_quantity * old_average) + total) / new_quantity
else:
new_quantity = shares
average = cost
portfolio["positions"][symbol] = {"quantity": new_quantity, "average_price": average}
portfolio["trades"].append({"side": "buy", "symbol": symbol, "quantity": str(shares), "price": str(cost)})
_save(path, _serialize(portfolio))
typer.echo(f"Bought {shares} shares of {symbol} at USD {cost:.4f} (paper trade only)")


def sell(
symbol: Annotated[str, typer.Option("--symbol")],
quantity: Annotated[str, typer.Option("--quantity")],
price: Annotated[str, typer.Option("--price")],
state: Annotated[Optional[str], typer.Option("--state", help="State file override")] = None,
):
"""Record a local paper sell; no real trade is placed."""
path = Path(state).expanduser() if state else _default_state_path()
portfolio = _deserialize(_load(path))
symbol = _symbol(symbol)
shares = _decimal(quantity, "quantity")
proceeds = _decimal(price, "price")
if shares <= 0:
raise typer.BadParameter("quantity must be greater than zero")
if proceeds <= 0:
raise typer.BadParameter("price must be greater than zero")

existing = portfolio["positions"].get(symbol)
if not existing or shares > existing["quantity"]:
typer.echo("Insufficient shares for this paper sell.", err=True)
raise typer.Exit(1)

remaining = existing["quantity"] - shares
if remaining == 0:
del portfolio["positions"][symbol]
else:
existing["quantity"] = remaining
portfolio["cash"] += shares * proceeds
portfolio["trades"].append({"side": "sell", "symbol": symbol, "quantity": str(shares), "price": str(proceeds)})
_save(path, _serialize(portfolio))
typer.echo(f"Sold {shares} shares of {symbol} at USD {proceeds:.4f} (paper trade only)")


def recommend(
symbol: Annotated[str, typer.Option("--symbol")],
state: Annotated[Optional[str], typer.Option("--state", help="State file override")] = None,
):
"""Show a deterministic local paper-trading recommendation."""
path = Path(state).expanduser() if state else _default_state_path()
portfolio = _deserialize(_load(path))
symbol = _symbol(symbol)
position = portfolio["positions"].get(symbol)
if position:
action = "HOLD"
rationale = f"position exists with {position['quantity']} shares; no external market data is used"
else:
action = "BUY" if portfolio["cash"] > 0 else "HOLD"
rationale = "no current position and available USD cash; no external market data is used"
typer.echo(f"Recommendation: {action} {symbol}")
typer.echo(rationale)


def paper_trading(
ctx: typer.Context,
state: Annotated[Optional[str], typer.Option("--state", help="State file override")] = None,
):
"""Manage a local-only USD paper-trading portfolio."""
pass


def register(app: typer.Typer):
group = typer.Typer(help="Local-only USD paper trading (no real trades)")
group.command()(init)
group.command()(status)
group.command()(buy)
group.command()(sell)
group.command()(recommend)
app.add_typer(group, name="paper-trading")
99 changes: 99 additions & 0 deletions tests/test_paper_trading.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0

import json

from typer.testing import CliRunner

from colab_cli.cli import app


runner = CliRunner()


def test_paper_trading_init_buy_sell_status(tmp_path):
state = tmp_path / "paper-trading.json"
result = runner.invoke(app, ["paper-trading", "--state", str(state), "init", "--balance", "1000"])
assert result.exit_code == 0
assert "USD 1000.00" in result.output

result = runner.invoke(app, ["paper-trading", "--state", str(state), "buy", "--symbol", "SXBT", "--quantity", "10", "--price", "0.55"])
assert result.exit_code == 0

result = runner.invoke(app, ["paper-trading", "--state", str(state), "status"])
assert result.exit_code == 0
assert "USD 994.50" in result.output
assert "SXBT" in result.output

result = runner.invoke(app, ["paper-trading", "--state", str(state), "sell", "--symbol", "SXBT", "--quantity", "4", "--price", "0.60"])
assert result.exit_code == 0

persisted = json.loads(state.read_text())
assert persisted["cash"] == "994.50" or persisted["cash"] == "997.50"
assert persisted["positions"]["SXBT"]["quantity"] == "6"


def test_paper_trading_initialization_reset_requires_force(tmp_path):
state = tmp_path / "paper-trading.json"
runner.invoke(app, ["paper-trading", "--state", str(state), "init", "--balance", "100"])
result = runner.invoke(app, ["paper-trading", "--state", str(state), "init", "--balance", "200", "--force"])
assert result.exit_code == 0
assert "USD 200.00" in result.output


def test_paper_trading_insufficient_funds(tmp_path):
state = tmp_path / "paper-trading.json"
runner.invoke(app, ["paper-trading", "--state", str(state), "init"])
result = runner.invoke(app, ["paper-trading", "--state", str(state), "buy", "--symbol", "SXBT", "--quantity", "100", "--price", "0.75"])
assert result.exit_code == 1
assert "Insufficient funds" in result.output


def test_paper_trading_insufficient_shares(tmp_path):
state = tmp_path / "paper-trading.json"
runner.invoke(app, ["paper-trading", "--state", str(state), "init"])
runner.invoke(app, ["paper-trading", "--state", str(state), "buy", "--symbol", "SXBT", "--quantity", "2", "--price", "0.50"])
result = runner.invoke(app, ["paper-trading", "--state", str(state), "sell", "--symbol", "SXBT", "--quantity", "3", "--price", "0.55"])
assert result.exit_code == 1
assert "Insufficient shares" in result.output


def test_paper_trading_invalid_quantity_and_price(tmp_path):
state = tmp_path / "paper-trading.json"
runner.invoke(app, ["paper-trading", "--state", str(state), "init"])
result = runner.invoke(app, ["paper-trading", "--state", str(state), "buy", "--symbol", "SXBT", "--quantity", "0", "--price", "0.50"])
assert result.exit_code == 1
assert "quantity" in result.output.lower()
result = runner.invoke(app, ["paper-trading", "--state", str(state), "buy", "--symbol", "SXBT", "--quantity", "1", "--price", "-1"])
assert result.exit_code == 1
assert "price" in result.output.lower()


def test_paper_trading_recommendation_output(tmp_path):
state = tmp_path / "paper-trading.json"
runner.invoke(app, ["paper-trading", "--state", str(state), "init"])
result = runner.invoke(app, ["paper-trading", "--state", str(state), "recommend", "--symbol", "SXBT"])
assert result.exit_code == 0
assert "SXBT" in result.output
assert "HOLD" in result.output or "BUY" in result.output or "SELL" in result.output


def test_paper_trading_missing_state(tmp_path):
state = tmp_path / "missing.json"
result = runner.invoke(app, ["paper-trading", "--state", str(state), "status"])
assert result.exit_code == 1
assert "not initialized" in result.output.lower()


def test_paper_trading_never_requests_credentials(tmp_path, mocker):
state = tmp_path / "paper-trading.json"
auth = mocker.patch("colab_cli.auth.get_credentials")
network = mocker.patch("requests.get")
runner.invoke(app, ["paper-trading", "--state", str(state), "init"])
auth.assert_not_called()
network.assert_not_called()