Exclusive 22% OFF All Quantra by QuantInsti Courses for IBridgePy Users Master algorithmic trading from beginner to advanced — Python for trading, machine learning strategies, options trading, and more.
HUI22 Use HUI22 for 22% off
HUI7 Stack HUI7 for an additional 7% off
Browse Courses →
← Back to Blog

How to Automatically Update Your IBridgePy Portfolio Every Day with Python

December 1, 2026 · Tutorials
Python API Tutorial

Automate Daily Updates to Your Live IBridgePy Portfolio

Publish end-of-day cash, holdings, and Net Asset Value (NAV) to your public IBridgePy Portfolio page—like the live DigitalShare LAB (DLAB) strategy—with a single Python HTTP call scheduled after US market close.

Every strategy hosted on IBridgePy Portfolio tracks its daily equity curve, cash balance, positions, and cumulative return compared against the SPY benchmark. Instead of manually sending CSV files or spreadsheets, you can update your strategy automatically every trading day with a 30-line Python script.

What You Need Before You Start

  1. Your IBridgePy API Key: Log in at ibridgepy.com/home/ and click Show / Copy inside the API Key card. Your key can update any strategy owned by your account.
  2. Your Strategy Slug: Copy the final segment of your portfolio URL:
    https://ibridgepy.com/portfolio/<username>/<strategy-slug>/
    For DigitalShare LAB (DLAB), the strategy slug is digitalshare-lab-dlab. (Strategy UUIDs are also accepted.)
  3. Python 3.9+ and requests: Install with pip install requests (and pip install tzdata on Windows if needed for US Eastern time).

Step 1: Understand the Portfolio Snapshot API

To publish or update a trading day's snapshot, send an authenticated HTTP POST request with a JSON body to:

POST https://ibridgepy.com/portfolio/snapshot/
Headers:
  Content-Type: application/json
  X-API-Key: <YOUR_IBRIDGEPY_API_KEY>
Field Type Required Description & Example
strategy string Yes Your strategy slug (e.g., "digitalshare-lab-dlab") or strategy UUID.
date string Yes Trading date in ISO format YYYY-MM-DD (e.g., "2026-12-01").
cash float Yes End-of-day cash balance in USD (e.g., 1007445.87).
positions list of strings Optional Holdings list such as ["Stocks:1@21793.20", "Options:1@40217.01"] or ["SPY:56"]. Use [] for 100% cash. Serialized JSON string must be ≤ 500 characters.
action string Optional Human-readable note shown in the Daily History table (max 500 chars), e.g., "Equities: $66,332.21 | Cash: $1,007,445.87".
total_value float Optional Automatically calculated on the server as round(cash + sum(position_values), 2) and returned in the JSON response.

Step 2: Choose the Right positions Format

Each entry in positions follows either TICKER:QTY or LABEL:QTY@PRICE. Pick the style that best matches your portfolio:

Option A: Asset-Class Buckets (Best for Multi-Asset & Options)

Used by portfolios like DigitalShare LAB (DLAB) that hold stocks, ETFs, and options. Set quantity to 1 and put each bucket's exact market value after @:

"positions": [
  "Stocks:1@21793.20",
  "Options:1@40217.01",
  "ETFs:1@4322.00"
]

Option B: US Stock / ETF Tickers (Auto-Priced)

For standard US equities and ETFs, send just TICKER:QTY. IBridgePy automatically looks up the official daily closing price and computes your total NAV:

"positions": [
  "SPY:56",
  "TLT:120",
  "SMH:35"
]
Important Note on Options & Inline Prices (@PRICE):
  • The server computes each holding's market value as quantity × price. For US equity option contracts (which represent 100 shares per contract), either multiply the option quote by 100 (for example, 7 contracts quoted at $2.51 = "SOXL 105C 20NOV26:7@251.00") or report total option market value as "Options:1@1757.00".
  • For standard US stock tickers tracked in IBridgePy's daily market database, the server prioritizes the official market closing price and falls back to your inline @PRICE if a ticker is not in the database.
  • If your portfolio is 100% cash on a given day, pass "positions": [] and your total_value will equal cash.

Step 3: Complete Python Script (update_portfolio.py)

Save the script below as update_portfolio.py. It skips weekends automatically, uses US Eastern time for the trading date, retries transient network hiccups, and prints the verified total NAV returned by the server.

from __future__ import annotations

import datetime as dt
import os
import time
from zoneinfo import ZoneInfo

import requests

API_URL = "https://ibridgepy.com/portfolio/snapshot/"
STRATEGY_SLUG = "digitalshare-lab-dlab"  # Replace with your own strategy slug
EASTERN = ZoneInfo("America/New_York")


def upload_daily_snapshot(
    strategy: str,
    cash: float,
    positions: list[str],
    action: str = "",
    trading_date: str | None = None,
    api_key: str | None = None,
    max_retries: int = 3,
) -> dict:
    """Publish or update a single day's portfolio snapshot on IBridgePy."""
    api_key = api_key or os.environ.get("IBRIDGEPY_API_KEY")
    if not api_key:
        raise RuntimeError(
            "Missing IBRIDGEPY_API_KEY. Set it as an environment variable "
            "using the API Key from https://ibridgepy.com/home/."
        )

    if trading_date is None:
        now_et = dt.datetime.now(EASTERN)
        if now_et.weekday() >= 5:
            print(f"Skipping weekend date {now_et.date()} (market closed).")
            return {}
        trading_date = now_et.date().isoformat()

    payload = {
        "strategy": strategy,
        "date": trading_date,
        "cash": round(float(cash), 2),
        "positions": positions,
        "action": action[:500],
    }

    headers = {
        "Content-Type": "application/json",
        "X-API-Key": api_key,
    }

    for attempt in range(1, max_retries + 1):
        try:
            resp = requests.post(API_URL, json=payload, headers=headers, timeout=20)
            if resp.status_code in (200, 201):
                result = resp.json()
                verb = "Created" if resp.status_code == 201 else "Updated"
                print(
                    f"[{verb}] {strategy} | {result['date']} | "
                    f"NAV: ${result['total_value']:,.2f} | Cash: ${result['cash']:,.2f}"
                )
                return result
            if resp.status_code in (400, 401, 403):
                # Client/auth errors will not succeed on retry
                raise RuntimeError(f"API error {resp.status_code}: {resp.text}")
            resp.raise_for_status()
        except requests.RequestException as exc:
            if attempt == max_retries:
                raise
            wait_sec = 2 ** attempt
            print(f"Attempt {attempt} failed ({exc}); retrying in {wait_sec}s...")
            time.sleep(wait_sec)


def get_todays_portfolio_numbers() -> tuple[float, list[str], str]:
    """Replace this function with your broker API, CSV parser, or database query."""
    cash = 1007445.87
    stocks_value = 21793.20
    options_value = 40217.01
    etfs_value = 4322.00

    positions = []
    if stocks_value:
        positions.append(f"Stocks:1@{stocks_value:.2f}")
    if options_value:
        positions.append(f"Options:1@{options_value:.2f}")
    if etfs_value:
        positions.append(f"ETFs:1@{etfs_value:.2f}")

    equities_total = stocks_value + options_value + etfs_value
    action = f"Equities: ${equities_total:,.2f} | Cash: ${cash:,.2f}"
    return cash, positions, action


if __name__ == "__main__":
    cash, positions, action = get_todays_portfolio_numbers()
    upload_daily_snapshot(
        strategy=STRATEGY_SLUG,
        cash=cash,
        positions=positions,
        action=action,
    )

Test Your Script Locally First

Set your API key in your terminal (never hardcode it inside a committed script) and run it once:

# Linux / macOS
export IBRIDGEPY_API_KEY="your-api-key-from-ibridgepy-home"
python3 update_portfolio.py

# Windows PowerShell
$env:IBRIDGEPY_API_KEY="your-api-key-from-ibridgepy-home"
python update_portfolio.py

You should see output confirming the upload:

[Created] digitalshare-lab-dlab | 2026-12-01 | NAV: $1,073,778.08 | Cash: $1,007,445.87

Step 4 (Optional): Push Directly from Your Live IBridgePy / Interactive Brokers Strategy

If your strategy already runs in IBridgePy connected to Interactive Brokers (TWS or IB Gateway), you can schedule the upload right inside initialize(context) to run automatically every day right before or at market close:

import os
import requests


def initialize(context):
    context.strategy_slug = "digitalshare-lab-dlab"
    # Upload portfolio snapshot every trading day 1 minute before market close
    schedule_function(
        push_daily_snapshot,
        date_rules.every_day(),
        time_rules.market_close(minutes=1),
    )


def push_daily_snapshot(context, data):
    cash = float(context.portfolio.cash)
    positions_list = []
    holdings_value = 0.0

    for security, pos in get_all_positions().items():
        if pos.amount == 0:
            continue
        # For stocks/ETFs, IBridgePy server can auto-price TICKER:QTY,
        # or include @PRICE for exact broker mark-to-market valuation.
        price = float(data.current(security, "price"))
        qty = int(pos.amount)
        multiplier = 100.0 if security.secType == "OPT" else 1.0
        unit_value = round(price * multiplier, 2)
        positions_list.append(f"{security.symbol}:{qty}@{unit_value:.2f}")
        holdings_value += qty * unit_value

    payload = {
        "strategy": context.strategy_slug,
        "date": get_datetime("US/Eastern").strftime("%Y-%m-%d"),
        "cash": round(cash, 2),
        "positions": positions_list,
        "action": f"Holdings: ${holdings_value:,.2f} | Cash: ${cash:,.2f}",
    }

    resp = requests.post(
        "https://ibridgepy.com/portfolio/snapshot/",
        json=payload,
        headers={"X-API-Key": os.environ["IBRIDGEPY_API_KEY"]},
        timeout=20,
    )
    resp.raise_for_status()
    print("IBridgePy Portfolio updated:", resp.json())

Step 5: Run It Automatically Every Trading Day

Schedule your script to run Monday through Friday between 4:15 PM and 5:00 PM US Eastern Time, once your broker's end-of-day balances have settled. Choose whichever scheduler fits your setup:

Method 1: Linux / macOS (cron)

Open your crontab with crontab -e and add the following lines to run at 4:30 PM New York time every weekday:

CRON_TZ=America/New_York
IBRIDGEPY_API_KEY=your-api-key-here
30 16 * * 1-5 /usr/bin/python3 /home/user/update_portfolio.py >> /home/user/portfolio_update.log 2>&1

Tip: If your system's cron does not support CRON_TZ, convert 4:30 PM ET to your server's timezone (for UTC, that is 21:30 in winter / 20:30 during daylight saving time).

Method 2: Windows Task Scheduler

  1. Add IBRIDGEPY_API_KEY under Start → Edit environment variables for your account.
  2. Open Task Scheduler and click Create Task…
  3. On the Triggers tab, click New → Weekly → select Monday–Friday at 4:30 PM ET (adjusted to your local clock).
  4. On the Actions tab, choose Start a program:
    Program/script: C:\Python311\python.exe (your Python path)
    Add arguments: C:\scripts\update_portfolio.py
  5. Click OK, then right-click the task and choose Run to test it immediately.

Method 3: GitHub Actions (Cloud-Hosted, No Server Needed)

Store IBRIDGEPY_API_KEY in your private repository under Settings → Secrets and variables → Actions, then add .github/workflows/daily_portfolio_update.yml:

name: Daily IBridgePy Portfolio Update

on:
  schedule:
    # 21:30 UTC Mon-Fri (4:30 PM EST / 5:30 PM EDT)
    - cron: "30 21 * * 1-5"
  workflow_dispatch: # Allows manual one-click test runs

jobs:
  upload:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.11"
      - run: pip install requests
      - name: Upload daily snapshot
        env:
          IBRIDGEPY_API_KEY: ${{ secrets.IBRIDGEPY_API_KEY }}
        run: python update_portfolio.py

Step 6: Verify Your Update Programmatically

You can confirm your latest snapshot is live either by refreshing your portfolio page in a browser or by querying your strategy's public JSON data endpoint:

import requests

url = "https://ibridgepy.com/portfolio/wtxrc21m/digitalshare-lab-dlab/data/"
snapshots = requests.get(url, timeout=15).json()
print("Total trading days recorded:", len(snapshots))
print("Latest snapshot:", snapshots[-1])

Frequently Asked Questions & Troubleshooting

What happens if I run the script twice on the same day?

The endpoint is idempotent (upsert by strategy + date). The first upload for a date returns HTTP 201 Created, and any subsequent upload for that same date updates the existing record and returns HTTP 200 OK—no duplicate rows are ever created.

Why didn't today's snapshot appear on the chart immediately after I posted it?

To keep portfolio charts free of weekend and US market holiday artifacts, IBridgePy displays snapshots for verified US market trading days (matched against daily SPY market close data). Your POST is saved immediately, and today's point automatically appears on the chart as soon as that trading day's closing bar is ingested after US market close.

Can I backfill historical dates with Python?

Yes! Loop over your historical records in chronological order, pass each date's YYYY-MM-DD string into upload_daily_snapshot(..., trading_date=row_date), and add a brief pause (time.sleep(0.2)) between requests.

How do I fix 401, 403, or 400 errors?
  • 401 Unauthorized: Your X-API-Key header is missing or invalid. Copy your exact key from ibridgepy.com/home/.
  • 403 Forbidden: Your API key belongs to a different user account than the strategy owner. Make sure you are logged into the account that owns the strategy.
  • 400 Bad Request: Check the JSON error message—most commonly caused by a typo in strategy, a non-YYYY-MM-DD date, or a positions string exceeding 500 characters.

Want to Track Your Own Strategy on IBridgePy Portfolio?

Explore live community strategies, grab your personal API key, or reach out to IBridgePy@gmail.com to onboard your strategy page.