Skip to content
Connect > Client Libraries > Python Client > Use Cases

Use Case: Real-Time Risk and P&L Loop

This use case builds a Python risk loop for 3forge Enterprise that keeps positions and P&L current as trades and prices change.

Prerequisites

  • Python 3.14 with the pyami-3forge package. See the Python client.
  • A client certificate the server accepts, with client.crt.pem, client.key.pem, and the server's 3forge.pub in the working directory. See Connecting and Securing a Client.

How it fits together

The program works in 3 parts:

  1. The program drops and creates 3 tables: RiskMarks (prices), RiskTrades, and RiskPnL (results). It checks every sql() result and stops on an error.
  2. It subscribes to RiskMarks and RiskTrades. The listener puts each update on a queue.
  3. A worker thread keeps a copy of both tables, merged by row id, and rewrites RiskPnL after each batch of changes.

The work happens on the worker thread because every callback runs on the client's single callback thread: a slow callback would hold up every later update. See Callbacks and threads.

1. Create the connection helper

The program connects through a helper that opens only the connections it asks for.

  1. Save the following code as connect.py in the working directory:

    from pyami.rt.ami_client import (AmiClient, AmiCluster, AmiDatabaseConfig,
                                     AmiPublicationConfig, AmiSslOptions,
                                     AmiSubscriptionConfig, Options)
    
    HOST = "localhost"
    KEYS = AmiSslOptions(trusted_server_pub_file="3forge.pub",
                         client_cert_file="client.crt.pem",
                         client_key_file="client.key.pem")
    
    
    def connect(listener, sql=False, center=False, relay=False, login_id="my_app"):
        """Return a client with cluster "N1" connected to the requested listeners."""
        cluster = AmiCluster("N1", HOST)
        if sql:
            config = AmiDatabaseConfig("3280", True, "demo", "demo123")
            config.shards[0].ssl = KEYS
            cluster.database_config = config
        if center:
            config = AmiSubscriptionConfig("3270", True)
            config.shards[0].ssl = KEYS
            cluster.subscription_config = config
        if relay:
            config = AmiPublicationConfig("3289", True, login_id, int(Options.UNIX_MODE))
            config.shards[0].ssl = KEYS
            cluster.publication_config = config
        client = AmiClient()
        client.add_listener(listener)
        client.add_cluster(cluster, sync=True)
        return client
    
  2. Confirm that the helper imports: run python -c "import connect", and the command returns with no output.

2. Write the risk loop

The risk loop creates its tables, subscribes, and makes the changes that drive it. It checks every sql() result, because sql() returns an error rather than raising one.

  1. Save the following code as risk_loop.py, beside connect.py. The program runs in stage 3:

    import queue
    import threading
    import time
    
    from connect import connect
    
    work = queue.Queue()
    rows = {"RiskMarks": {}, "RiskTrades": {}}   # table -> row id -> row
    
    
    class Listener:
        def on_update(self, client, name, update):
            # Runs on the client's callback thread: hand the change to the worker and return.
            work.put((update.table_name, update.action, update.id,
                      dict(zip(update.field_names, update.row_data))))
    
        def on_log(self, client, name, level, message):
            if level >= 3:
                print("error:", name, message)
    
    
    client = connect(Listener(), sql=True, center=True)
    
    
    def run(statement):
        result = client.sql("N1", statement)
        if "error" in result:
            raise RuntimeError(f"{statement}: {result['error']}")
        return result
    
    
    for table in ("RiskPnL", "RiskTrades", "RiskMarks"):
        run(f"DROP TABLE IF EXISTS {table}")
    run("CREATE PUBLIC TABLE RiskMarks (sym String, px Double)")
    run("CREATE PUBLIC TABLE RiskTrades (sym String, qty Long, px Double)")
    run("CREATE PUBLIC TABLE RiskPnL (sym String, position Long, pnl Double)")
    run('INSERT INTO RiskMarks VALUES ("IBM", 183.0), ("AAPL", 201.0)')
    
    
    def write_risk():
        marks = {row["sym"]: row["px"] for row in rows["RiskMarks"].values()}
        positions = {}
        for trade in rows["RiskTrades"].values():
            qty, cost = positions.get(trade["sym"], (0, 0.0))
            positions[trade["sym"]] = (qty + trade["qty"], cost + trade["qty"] * trade["px"])
        run("DELETE FROM RiskPnL")
        for sym, (qty, cost) in positions.items():
            pnl = round(qty * marks[sym] - cost, 2)
            run(f'INSERT INTO RiskPnL VALUES ("{sym}", {qty}, {pnl})')
    
    
    def worker():
        while True:
            table, action, row_id, fields = work.get()
            if table is None:
                return
            if action == 3:
                rows[table].pop(row_id, None)
            else:
                rows[table].setdefault(row_id, {}).update(fields)
            if work.empty():
                write_risk()
    
    
    thread = threading.Thread(target=worker)
    thread.start()
    client.subscribe("N1", ["RiskMarks", "RiskTrades"], sync=True)
    
    run('INSERT INTO RiskTrades VALUES ("IBM", 100, 180.0), ("AAPL", -50, 205.0)')
    time.sleep(1)
    print(run("SELECT * FROM RiskPnL ORDER BY sym"))
    
    run('UPDATE RiskMarks SET px = 190.0 WHERE sym == "IBM"')
    time.sleep(1)
    print(run("SELECT * FROM RiskPnL ORDER BY sym"))
    
    work.put((None, None, None, None))
    thread.join()
    for table in ("RiskPnL", "RiskTrades", "RiskMarks"):
        run(f"DROP TABLE {table}")
    client.remove_cluster("N1", sync=True)
    

The program relies on 2 behaviors:

  • Updates merge by row id: the price change on RiskMarks arrives with only the px column, so the worker finds the symbol in the row it already holds.
  • One write covers a batch of changes: the worker writes RiskPnL only when the queue is empty, so several changes arriving together cause one write.

3. Run it

This stage runs the loop and checks the P&L it writes.

  1. Run the program: python risk_loop.py.
  2. Check that it prints the P&L after the trades, then again after the IBM price moves to 190.0:

    {'sym': ['AAPL', 'IBM'], 'position': array([-50, 100]), 'pnl': array([200., 300.])}
    {'sym': ['AAPL', 'IBM'], 'position': array([-50, 100]), 'pnl': array([ 200., 1000.])}
    

IBM's P&L is its 100 shares at the mark, less their cost: 100 x 183.0 - 18,000 = 300, then 100 x 190.0 - 18,000 = 1,000.

Result

The program recomputed positions and P&L from live changes to 2 tables and wrote them back, without blocking the callback thread. It drops its tables before it exits.