Use Case: Market Data Publisher and Subscriber¶
This use case builds a Python market data feed for 3forge Enterprise: one program publishes quotes, and another keeps a board of the latest price for each symbol.
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 2 programs meet in one table:
- The publisher sends each quote to the Relay with
publish, using the symbol as the object id. - The first quote creates the table
MarketQuotes, with anIcolumn holding the id. - The subscriber subscribes to
MarketQuotesand merges each update into a dictionary by row id.
The publisher lets its first quote create the table. A table created in advance must have an I column and a column for every field, or the quotes are dropped; see Publishing and the acknowledgement.
Both programs are headless
Neither program draws a chart or a user interface. To chart the data, build a dashboard on the table in 3forge Enterprise.
1. Create the connection helper¶
Both programs connect through one helper, which opens only the connections a program 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 publisher¶
The publisher moves 3 prices at random and publishes them every half second, 20 times.
-
Save the following code as
publisher.py, besideconnect.py. The program runs in stage 4:
The Relay replies OK, object accepted to every quote, in on_message_received, and the listener prints only replies with a status other than 0. The helper sets UNIX_MODE on the Relay connection, so the replies arrive there against a Relay on Windows too; see Checking what happened to a published object.
3. Write the subscriber¶
The subscriber keeps one row per symbol and prints the board every 2 seconds.
-
Save the following code as
subscriber.py, besideconnect.py. The program runs in stage 4:
An update carries only the columns that changed, so the subscriber merges each one into the row with the same id.
4. Run both programs¶
This stage runs the publisher and the subscriber side by side.
- Start the publisher:
python publisher.py. - Within a few seconds, in a second terminal, start the subscriber:
python subscriber.py. -
Check that the subscriber prints a board of 3 symbols whose prices and tick numbers change, then stays at tick
19once the publisher printspublished 20 ticks:
The prices at each tick are the same on every run, because the publisher uses a fixed seed; the ticks the board shows depend on when the subscriber starts.
Result¶
One program published live quotes and another kept a latest-price board from them. The table MarketQuotes stays after both programs exit; drop it with DROP TABLE MarketQuotes.