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-3forgepackage. See the Python client. - A client certificate the server accepts, with
client.crt.pem,client.key.pem, and the server's3forge.pubin the working directory. See Connecting and Securing a Client.
How it fits together¶
The program works in 3 parts:
- The program drops and creates 3 tables:
RiskMarks(prices),RiskTrades, andRiskPnL(results). It checks everysql()result and stops on an error. - It subscribes to
RiskMarksandRiskTrades. The listener puts each update on a queue. - A worker thread keeps a copy of both tables, merged by row id, and rewrites
RiskPnLafter 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.
-
Save the following code as
connect.pyin the working directory: -
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.
-
Save the following code as
risk_loop.py, besideconnect.py. The program runs in stage 3:
The program relies on 2 behaviors:
- Updates merge by row id: the price change on
RiskMarksarrives with only thepxcolumn, so the worker finds the symbol in the row it already holds. - One write covers a batch of changes: the worker writes
RiskPnLonly 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.
- Run the program:
python risk_loop.py. -
Check that it prints the P&L after the trades, then again after the IBM price moves to
190.0:
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.