Skip to content

ShaadyEmad/tradezero-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 

Repository files navigation

TradeZero Unofficial Python API

Python License PRs Welcome Unofficial

The first and only unofficial Python API for TradeZero, reverse-engineered from the TradeZero web platform. Enables full programmatic trading — login, market data, order placement, account info, and more.


Disclaimer

This project is not affiliated with, endorsed by, or officially supported by TradeZero in any way. It was built by reverse-engineering the TradeZero web application's internal HTTP traffic. Use at your own risk. The author takes no responsibility for financial losses, account restrictions, or API changes that may break this library. Always test in a paper/demo account before going live.


Features

  • Authentication — Username/password login with full 2FA (OTP) support
  • Market Data — Real-time Bid, Ask, Last, Volume, High, Low, Open, Close
  • Order Placement — Market, Limit, Stop, StopLimit, RangeOrder, MarketOnClose, LimitOnClose
  • Order Management — Check status, wait for fill, cancel orders
  • Account Info — Equity, Buying Power, P&L, Total Commissions
  • Human-friendly API — Pass plain strings like 'buy', 'limit', 'day' instead of numeric codes
  • Session handling — Persistent requests session with browser-like headers

Requirements


Installation

Option 1 — Clone with Git (Recommended)

git clone https://github.com/ShaadyEmad/tradezero-api.git
cd tradezero-api
pip install -r requirements.txt

Then import directly:

from tradezero import TradeZeroClient

Option 2 — Download the file manually

  1. Download tradezero.py from this repo
  2. Place it in your project folder
  3. Install dependencies:
pip install requests requests-toolbelt

Option 3 — pip install dependencies only (if you already have the file)

pip install -r requirements.txt

requirements.txt contents:

requests>=2.28.0
requests-toolbelt>=0.10.1

Virtual Environment (Best Practice)

# Create venv
python -m venv venv

# Activate (Windows)
venv\Scripts\activate

# Activate (Mac/Linux)
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

Quick Start

from tradezero import TradeZeroClient

client = TradeZeroClient(username="YOUR_USERNAME", password="YOUR_PASSWORD")

# Step 1: Login
status = client.login()

if status == "2fa":
    otp = input("Enter your 2FA code: ")
    client.submit_otp(otp)
elif status == "success":
    print("Logged in!")

# Step 2: Get market data
data = client.get_market_data("AAPL")
print(data)

# Step 3: Place a market buy order
order_id = client.place_order(
    symbol="AAPL",
    quantity=10,
    side="buy",
    order_type="market",
    time_in_force="day"
)

# Step 4: Wait for fill
success, avg_price, filled_qty, feedback = client.wait_for_order_status(order_id)
print(f"Filled {filled_qty} shares at ${avg_price}")

API Reference

TradeZeroClient(username, password, account_id=None)

Creates a new client instance. Does not log in automatically.

Parameter Type Description
username str Your TradeZero username
password str Your TradeZero password
account_id str Optional. Defaults to username if not provided
client = TradeZeroClient("myuser", "mypassword")
# or with explicit account ID
client = TradeZeroClient("myuser", "mypassword", account_id="myuser")

login() → str

Authenticates with TradeZero. Returns a status string — does not block for 2FA input.

Returns:

Value Meaning
"success" Logged in successfully, no 2FA required
"2fa" Login succeeded but 2FA OTP is required next
"failed" Wrong credentials or rejected by server
"error" Network/connection error
status = client.login()

if status == "2fa":
    otp = input("Enter OTP: ")
    client.submit_otp(otp)
elif status == "success":
    print("Ready to trade!")
elif status == "failed":
    print("Check your credentials.")

submit_otp(otp_code) → bool

Submits the 2FA OTP code after a login() call returned "2fa".

Parameter Type Description
otp_code str or int The 6-digit OTP code

Returns: True on success, False on failure.

success = client.submit_otp("123456")

get_market_data(symbol) → dict | None

Fetches real-time market data for a symbol.

Parameter Type Description
symbol str Stock ticker (e.g. "AAPL")

Returns: Dictionary with the following keys, or None on failure:

Key Description
symbol Ticker symbol
bid Current bid price
ask Current ask price
last Last traded price
volume Today's volume
high Today's high
low Today's low
open Today's open
close Previous day's close
data = client.get_market_data("TSLA")
print(f"TSLA Ask: {data['ask']}")

get_account_info() → dict | None

Fetches account equity, buying power, P&L, and total commissions paid.

Returns: Dictionary from TradeZero's PNL endpoint merged with buying power and commissions, or None on failure. Key fields include:

Key Description
bp Buying power
totalCommissions Total commissions paid today
(other PNL fields) Equity, realized/unrealized P&L
info = client.get_account_info()
print(f"Buying Power: ${info['bp']}")
print(f"Commissions: ${info['totalCommissions']}")

place_order(symbol, quantity, side, order_type, price, stop_price, time_in_force, open_close, route) → str | None

Places a trading order.

Parameter Type Default Description
symbol str required Stock ticker
quantity int required Number of shares
side str required "buy", "sell", or "short"
order_type str required See Order Types table
price float 0.0 Limit price (or take-profit price for Range orders)
stop_price float 0.0 Stop price (for Stop / StopLimit / Range orders)
time_in_force str "day" See Time In Force table
open_close str "open" "open" to open a position, "close" to close it
route str "SMART" Routing — "SMART" for stocks, "SMARTO" for options

Returns: A unique userOrderId string on success, None on failure.

order_id = client.place_order(
    symbol="NVDA",
    quantity=5,
    side="buy",
    order_type="limit",
    price=900.00,
    time_in_force="day"
)

get_order_status(target_id) → tuple

Looks up the current status of an order by its ID.

Parameter Type Description
target_id str The userOrderId returned by place_order

Returns: Tuple (status, avg_price, filled_qty, feedback)

Field Type Description
status str "Filled", "Rejected", "Canceled", "NotFound", "Error"
avg_price float Average fill price
filled_qty int Number of shares filled
feedback str Broker message / rejection reason
status, price, qty, msg = client.get_order_status(order_id)
print(f"Status: {status} | Price: {price} | Qty: {qty}")

wait_for_order_status(order_id) → tuple

Polls get_order_status every 2 seconds until the order resolves (filled, rejected, or canceled). Blocks until a definitive status is received.

Parameter Type Description
order_id str The userOrderId returned by place_order

Returns: Tuple (success, avg_price, filled_qty, feedback)

Field Type Description
success bool True if filled, False if rejected/canceled
avg_price float Average fill price
filled_qty int Number of shares filled
feedback str Broker message
success, price, qty, msg = client.wait_for_order_status(order_id)
if success:
    print(f"Filled {qty} @ ${price}")
else:
    print(f"Order failed: {msg}")

cancel_order(order_id) → bool

Cancels a pending order.

Parameter Type Description
order_id str The userOrderId returned by place_order

Returns: True on success, False on failure.

cancelled = client.cancel_order(order_id)

Reference Tables

Order Types

String Description
"market" Market order — fill at best price
"limit" Limit order — fill at price or better
"stop" Stop market — triggers at stop_price
"stoplimit" Stop limit — stop triggers limit entry
"range" Range order — take-profit + stop-loss
"marketonclose" Market On Close
"limitonclose" Limit On Close

Side

String Description
"buy" Buy / long
"sell" Sell / close long position
"short" Sell short (alias for "sell")

Time In Force (TIF)

String Description
"day" Day order — expires at market close
"day+" Day+ — extended hours day order
"gtc" Good Till Canceled
"gtc+" GTC+ — extended hours GTC
"gtx" Good Till Crossing (pre/post market)
"opg" Opening — execute at market open only

Examples

Buy Market Order

order_id = client.place_order("AAPL", 10, "buy", "market")
success, price, qty, msg = client.wait_for_order_status(order_id)

Buy Limit Order

order_id = client.place_order("AAPL", 10, "buy", "limit", price=180.50)

Short Sell with Stop Loss

# Short 100 shares of GME with a stop at $25
order_id = client.place_order(
    symbol="GME",
    quantity=100,
    side="short",
    order_type="stoplimit",
    price=20.00,       # limit price
    stop_price=25.00,  # stop trigger
    time_in_force="day"
)

Range Order (Take Profit + Stop Loss)

# Close long position with TP at $200, SL at $185
order_id = client.place_order(
    symbol="AAPL",
    quantity=10,
    side="sell",
    order_type="range",
    price=200.00,       # take profit
    stop_price=185.00,  # stop loss
    open_close="close"
)

Full Login Flow with 2FA

from tradezero import TradeZeroClient

client = TradeZeroClient("myuser", "mypassword")
status = client.login()

if status == "2fa":
    code = input("Enter 2FA OTP: ")
    if not client.submit_otp(code):
        raise Exception("OTP failed")
elif status != "success":
    raise Exception(f"Login failed: {status}")

# Now you're authenticated
info = client.get_account_info()
print(f"Buying Power: ${info['bp']:,.2f}")

Support the Project

If this library saved you time or helped your trading, consider buying me a coffee!

PayPal

Donate PayPal

👉 paypal.me/shaadyemad

Binance (Crypto)

Binance UID: 751730419

You can send any crypto donation directly to my Binance account using the UID above.


License

This project is licensed under the MIT License — see the LICENSE file for details.


Contact


Contributing

Pull requests are welcome! If the TradeZero API changes and something breaks, feel free to open an issue or submit a fix.

  1. Fork the repo
  2. Create your branch (git checkout -b fix/something)
  3. Commit your changes
  4. Open a Pull Request

Built with reverse engineering and a lot of packet sniffing. Not affiliated with TradeZero.

About

Description: Unofficial Python API for TradeZero brokerage — reverse-engineered from the web platform. Supports login, 2FA, market data, order placement, account info, and more.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages