Skip to content

chengyixu/cli-anything-firstrade

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Firstrade CLI bb-browser CLI-Anything

cli-anything-firstrade

The first and only CLI for Firstrade brokerage.
Trade stocks, view portfolio, manage orders — all from the command line.
Supports local, remote, headless, and cloud deployment.

FeaturesInstallationQuick StartAI TradingCloudArchitecture


Why?

Firstrade has no public API. No REST endpoints, no WebSocket feeds, no SDK. If you want to trade programmatically on Firstrade, you're stuck clicking buttons in a browser.

Until now.

cli-anything-firstrade gives you full programmatic access to your Firstrade brokerage account. Built with CLI-Anything methodology and powered by bb-browser, it controls the real Firstrade web interface via Chrome DevTools Protocol (CDP) — using your actual browser session with all your login cookies and authentication.

Features

  • First CLI for Firstrade — No other tool provides programmatic access to Firstrade
  • AI Automated Trading — JSON output mode enables AI agents to monitor, analyze, and execute trades autonomously
  • Full Brokerage Operations — Portfolio, positions, orders, balances, history, quotes, buy, sell, cancel
  • Interactive REPL — Beautiful terminal interface with command history, auto-suggest, and branded styling
  • Local + Remote + Cloud — Run on your Mac, a remote server, or a headless VPS
  • Real Browser Control — Uses your actual logged-in Chrome session (not a scraper or bot)
  • bb-browser Powered — CDP-based browser automation that websites can't distinguish from real users
  • CLI-Anything Ecosystem — Built following the CLI-Anything standard, installable via pip
  • Claude Code Skill — Built-in skill file for AI agent integration
  • Zero API Keys Required — Just your existing Firstrade login

Installation

Prerequisites

# 1. Install bb-browser (browser automation layer)
npm install -g bb-browser

# 2. Ensure Chrome is running (bb-browser connects to it via CDP)
# bb-browser daemon starts automatically when needed

Install the CLI

git clone https://github.com/chengyixu/cli-anything-firstrade.git
cd cli-anything-firstrade
pip install -e . --user --break-system-packages

Verify

firstrade --help
firstrade config  # Check connection status

Quick Start

Interactive REPL

firstrade
╭──────────────────────────────────────────────────────╮
│ ◆  cli-anything · Firstrade                          │
│    v1.0.0                                            │
│    Powered by bb-browser (CDP)                       │
│                                                      │
│    Type help for commands, quit to exit               │
╰──────────────────────────────────────────────────────╯

  ✓ Connected: bb-browser daemon connected at 127.0.0.1:19824

◆ firstrade ❯ portfolio
◆ firstrade ❯ positions
◆ firstrade ❯ trade buy AAPL 10
◆ firstrade ❯ quote TSLA

One-Shot Commands

# View portfolio
firstrade portfolio

# List positions
firstrade positions

# Account balances
firstrade balances

# Stock quote
firstrade quote AAPL

# Place trades
firstrade trade buy AAPL 10
firstrade trade sell TSLA 5 --type limit --price 300
firstrade trade buy NVDA 20 --type market --duration gtc

# Order management
firstrade orders
firstrade cancel-order 12345

# Transaction history
firstrade history

# JSON output (for scripting)
firstrade --json positions
firstrade --json balances

AI Automated Trading

The --json flag outputs machine-readable JSON, enabling AI agents, trading bots, and automation scripts to control Firstrade programmatically.

Example: Trading Bot

import subprocess
import json

def firstrade(cmd):
    """Run a Firstrade CLI command and return parsed JSON."""
    result = subprocess.run(
        f"firstrade --json {cmd}",
        shell=True, capture_output=True, text=True
    )
    return json.loads(result.stdout)

# Monitor portfolio
portfolio = firstrade("portfolio")
print(f"Total Value: {portfolio.get('total_value')}")

# Check positions
positions = firstrade("positions")
for row in positions.get("rows", []):
    print(f"  {row[0]}: {row[1]} shares @ {row[2]}")

# Get real-time quote
quote = firstrade("quote AAPL")
price = float(quote.get("price", "0").replace("$", "").replace(",", ""))

# Execute trade based on logic
if price < 150:
    firstrade("trade buy AAPL 10 --type market --no-confirm")

Example: Claude Code AI Agent

# Claude Code can directly use the firstrade skill:
# "Buy 10 shares of AAPL if it's below $150"

# The AI agent will:
# 1. firstrade --json quote AAPL
# 2. Parse the price
# 3. firstrade trade buy AAPL 10 --no-confirm (if condition met)

Example: Scheduled Portfolio Check

# crontab: Check portfolio every hour
0 * * * * firstrade --json portfolio >> /var/log/portfolio.jsonl

Trade Options

# Order types
firstrade trade buy AAPL 10 --type market              # Market (default)
firstrade trade buy AAPL 10 --type limit --price 150    # Limit
firstrade trade sell TSLA 5 --type stop --price 200     # Stop
firstrade trade buy NVDA 20 --type stop_limit --price 300  # Stop-limit

# Duration
firstrade trade buy AAPL 10 --duration day              # Day order (default)
firstrade trade buy AAPL 10 --duration gtc              # Good-til-cancelled
firstrade trade buy AAPL 10 --duration ext              # Extended hours

# Confirmation
firstrade trade buy AAPL 10                             # Asks for confirmation
firstrade trade buy AAPL 10 --no-confirm                # Skip (for automation)

Cloud Deployment

Run on a cloud server for 24/7 automated trading:

Your laptop                         Cloud Server (VPS/EC2/etc.)
┌─────────────┐     SSH/HTTPS      ┌──────────────────────────┐
│ firstrade   │ ──────────────────▶ │ bb-browser daemon        │
│ CLI         │    BB_HOST=server   │   ↕ CDP WebSocket        │
└─────────────┘                     │ Chrome (headless)        │
                                    └──────────────────────────┘

Quick Setup

# On the server:
npm install -g bb-browser
pip install cli-anything-firstrade
google-chrome-stable --headless=new --remote-debugging-port=9222 --no-sandbox &
bb-browser daemon --host 0.0.0.0 &

# From your laptop:
BB_HOST=your-server.com firstrade portfolio
BB_HOST=your-server.com firstrade trade buy AAPL 10

SSH Tunnel (Secure)

ssh -L 19824:localhost:19824 user@your-server
firstrade portfolio  # Tunneled to remote server

See CLOUD-SETUP.md for full instructions including Docker and systemd.

Architecture

┌──────────────────────────────────────────────────────────────────┐
│                        firstrade CLI                             │
│  Python/Click — commands, REPL, session state, trade logic       │
├──────────────────────────────────────────────────────────────────┤
│                     bb-browser backend                           │
│  Subprocess calls → bb-browser CLI → daemon (HTTP/CDP)           │
├──────────────────────────────────────────────────────────────────┤
│                     bb-browser daemon                            │
│  Node.js — persistent CDP WebSocket connection to Chrome         │
├──────────────────────────────────────────────────────────────────┤
│                     Chrome browser                               │
│  Local / Remote / Headless — your real logged-in session         │
└──────────────────────────────────────────────────────────────────┘

Two Interaction Modes

  1. CSS-selector mode (via eval): JavaScript runs directly in the page. Used for form filling, data extraction, and element clicks. Stable across sessions.
  2. Ref-based mode (via snapshot): Accessibility tree refs for native CDP interactions (keyboard/mouse events). Used for complex interactions.

Project Structure

cli-anything-firstrade/
├── setup.py                          # Package setup
├── CLOUD-SETUP.md                    # Cloud deployment guide
├── cli_anything/
│   └── firstrade/
│       ├── firstrade_cli.py          # Main CLI (Click groups)
│       ├── core/
│       │   ├── session.py            # Session state management
│       │   └── selectors.py          # CSS selectors & URLs
│       ├── utils/
│       │   ├── bb_backend.py         # bb-browser backend
│       │   └── repl_skin.py          # CLI-Anything REPL skin
│       └── skills/
│           └── SKILL.md              # AI agent skill file

Browser Control

Direct browser access for advanced use cases:

firstrade browser open URL            # Navigate
firstrade browser screenshot          # Capture page
firstrade browser eval "JS"           # Execute JavaScript
firstrade browser snapshot            # Accessibility tree
firstrade browser tabs                # List tabs
firstrade browser click SELECTOR      # Click by CSS selector
firstrade browser fill SEL VALUE      # Fill input field

Configuration

# Environment variables
export BB_HOST=127.0.0.1    # Daemon host (default: localhost)
export BB_PORT=19824        # Daemon port (default: 19824)
export BB_TAB=abc123        # Target specific tab

# CLI flags
firstrade --host server.com --port 19824 --tab abc123 portfolio

# Check configuration
firstrade config

Login

# If already logged in via Chrome (recommended):
firstrade login              # Detects existing session

# Programmatic login:
firstrade login -u USERNAME -p PASSWORD --pin PIN

Built With

License

MIT

Disclaimer

This tool is for personal use. Trading involves risk. Use automated trading at your own risk. This project is not affiliated with or endorsed by Firstrade Securities Inc.

About

The first and only CLI for Firstrade brokerage. Trade stocks, view portfolio, manage orders from the terminal. AI automated trading support. Powered by bb-browser + CLI-Anything.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages