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

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-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 2 programs meet in one table:

  1. The publisher sends each quote to the Relay with publish, using the symbol as the object id.
  2. The first quote creates the table MarketQuotes, with an I column holding the id.
  3. The subscriber subscribes to MarketQuotes and 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.

  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 publisher

The publisher moves 3 prices at random and publishes them every half second, 20 times.

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

    import random
    import time
    
    from connect import connect
    
    
    class Listener:
        def on_message_received(self, client, name, now, seqnum, status, message):
            if status != 0:
                print("relay:", name, status, message)
    
        def on_log(self, client, name, level, message):
            if level >= 3:
                print("error:", name, message)
    
    
    client = connect(Listener(), relay=True, login_id="quote_feed")
    
    prices = {"IBM": 183.50, "AAPL": 201.10, "MSFT": 412.00}
    random.seed(1)
    for tick in range(20):
        for sym, px in prices.items():
            prices[sym] = round(px * (1 + random.uniform(-0.002, 0.002)), 2)
            client.publish("N1", "MarketQuotes", sym, {"sym": sym, "px": prices[sym], "tick": tick})
        time.sleep(0.5)
    
    print("published 20 ticks")
    client.remove_cluster("N1", sync=True)
    

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.

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

    import time
    
    from connect import connect
    
    latest = {}
    
    
    class Listener:
        def on_update(self, client, name, update):
            if update.action == 3:
                latest.pop(update.id, None)
            else:
                latest.setdefault(update.id, {}).update(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)
    client.subscribe("N1", ["MarketQuotes"], sync=True)
    
    for _ in range(6):
        time.sleep(2)
        board = sorted((row.get("sym"), row.get("px"), row.get("tick")) for row in latest.values())
        print(board)
    
    client.remove_cluster("N1", sync=True)
    

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.

  1. Start the publisher: python publisher.py.
  2. Within a few seconds, in a second terminal, start the subscriber: python subscriber.py.
  3. Check that the subscriber prints a board of 3 symbols whose prices and tick numbers change, then stays at tick 19 once the publisher prints published 20 ticks:

    [('AAPL', 201.17, 8), ('IBM', 183.27, 8), ('MSFT', 410.46, 8)]
    [('AAPL', 200.78, 12), ('IBM', 183.09, 12), ('MSFT', 409.44, 12)]
    

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.