Skip to content
Connect > Client Libraries > Python Client

Python Client

The Python client library, the pyami-3forge package, connects a Python program to 3forge Enterprise to run SQL, write tables, subscribe to live updates, publish objects, and register commands.

Overview

The package has 3 ways in, all built on one native client:

The model behind it, clusters, connections, and the callback thread, is in Concepts.

Prerequisites

  • Python 3.14, on 64-bit Linux or Windows.
  • The package, installed from the Python Package Index with pip install pyami-3forge. It installs pandas and SQLAlchemy with it; the client needs pandas to start.
  • A client certificate the server accepts. See Connecting and Securing a Client.

Connecting

A program creates one AmiClient, adds a listener, and adds a cluster with a configuration for each connection it uses.

  1. Configure the connections and add the cluster:

    from pyami.rt.ami_client import (AmiClient, AmiCluster, AmiDatabaseConfig,
                                     AmiPublicationConfig, AmiSslOptions,
                                     AmiSubscriptionConfig)
    
    keys = AmiSslOptions(trusted_server_pub_file="3forge.pub",
                         client_cert_file="client.crt.pem",
                         client_key_file="client.key.pem")
    
    sql_config = AmiDatabaseConfig("3280", True, "demo", "demo123")
    sql_config.shards[0].ssl = keys
    center_config = AmiSubscriptionConfig("3270", True)
    center_config.shards[0].ssl = keys
    relay_config = AmiPublicationConfig("3289", True, "my_app", 0)
    relay_config.shards[0].ssl = keys
    
    cluster = AmiCluster("N1", "localhost")
    cluster.database_config = sql_config
    cluster.subscription_config = center_config
    cluster.publication_config = relay_config
    
    class Listener:
        def on_log(self, client, name, level, message):
            if level >= 3:
                print("error:", name, message)
    
    client = AmiClient()
    client.add_listener(Listener())
    client.add_cluster(cluster, sync=True)
    
  2. Check that client.sql("N1", "SELECT 1") returns {'1': array([1], dtype=int32)}.

The listener can be any object: the client calls a method only if the object has it. Exceptions raised in a callback are printed and do not reach your code.

Configuration Arguments
AmiDatabaseConfig port_or_service, use_ssl, username, password, then optionally query_timeout_ms=30000, query_limit=10000, db=""
AmiSubscriptionConfig port_or_service, use_ssl, then optionally username="", password=""
AmiPublicationConfig port_or_service, use_ssl, login_id, options. All 4 are required; pass 0 for no options, or int(Options.UNIX_MODE) for a Relay on Windows (see Checking what happened to a published object)

Check the first query, not the connection

A client whose certificate the server refuses is still reported as connected: add_cluster returns, on_connect fires, and sql() returns {}. The only other sign is an on_log error, Synchronous operation failed: ....

Running SQL

To run SQL from Python, call sql(cluster, statement), which returns a dictionary.

result = client.sql("N1", "SELECT sym, px FROM Quotes")
# {'sym': ['IBM', 'AAPL'], 'px': array([183.5, 201.1])}
Statement Returns
A query One key per column. Text columns are lists; other columns are numpy arrays (see Column types)
An insert, update, or delete that changed rows {'rows_affected': n}, plus generated_keys for a table with an AUTOGEN index
DDL, a change that changed no rows, or a cluster name the client does not have {}
A failed statement {'error': '[shard 0] 009-EXCEPTION: Unknown table: Quotes'}, with no other keys

Check that the result holds the columns, not an error key: sql() does not raise on a server error. To load a result into pandas, pass it to pandas.DataFrame, or use the query builder with as_frame=True.

  • {} has several meanings: it is returned for DDL, for a change that changed no rows, for a cluster name the client does not have (with an on_log error Failed to execute SQL query: Cluster not found [<name>]), and when the server refused the certificate.
  • Several statements run in one call: sql() accepts statements separated by ;. If a later one fails, the earlier ones stay committed and the result holds only the error.
  • A NULL string comes back as "", the same as an empty string.

sql_async(cluster, statement, callback) runs the statement in the background and calls callback(result) on the callback thread. Requests on one cluster are queued and run in order, so several threads can call sql() at once.

Results stop at 10,000 rows without saying so

A query returns at most query_limit rows, 10,000 by default, and nothing in the result shows that rows were left out. Raise query_limit on the configuration, or count first with SELECT count(*).

How each call reports errors

The client reports a failure in one of 3 ways, depending on the call:

Call On a server error
sql(), sql_insert(), sql_bulk_insert(), sql_replace() Returns {'error': '...'} for an error the server or the table check reports
The same 3 write calls, for data they cannot send Raises RuntimeError, e.g: All columns must have the same row count
select(), run() Raises RuntimeError
publish(), publish_batch(), remove(), register_command() Returns None; the Relay's reply arrives in on_message_received or on_log (see Checking what happened to a published object)

Writing tables

3 calls upload rows in bulk. Each takes the cluster, a table name, and the data as a dictionary of equal-length lists or numpy arrays, or a pandas DataFrame.

Call Missing table Existing table
sql_insert(cluster, table, data, create_table_if_not_exist=True) Creates it The data's columns must match the table's exactly; extra or missing columns return an error
sql_bulk_insert(cluster, table, data) Returns {'error': '... Table not found for Upload: <table>'} Appends the rows. Columns missing from the data are stored as 0 or 0.0
sql_replace(cluster, table, data, suffix='') Creates it, with suffix as its table options Deletes every row, keeping the table and its indexes, then inserts the new rows. Columns missing from the data are stored as 0 or 0.0
client.sql_insert("N1", "Prices", {"sym": ["IBM", "AAPL"], "px": [183.5, 201.1]})
# {'rows_affected': 2}

Check that the call returned rows_affected, the number of rows written.

A column mismatch on sql_insert lists every difference, and is also logged to on_log as an error:

{'error': "schema of table 'Prices' differs from the data: column 'zz' (Double) is not in the table; table column 'px' (Double) is missing from the data"}

When sql_insert creates a table, it types each column from its values: str as String, float as Double, int as Long, and bool as Boolean. batch_size is accepted and ignored.

suffix takes table options without the word USE, e.g: suffix='RefreshPeriodMs="500"'. It is used only when sql_replace creates the table. A suffix the server does not accept fails with Table not found for Upload: <table>, and no table is created.

sql_replace deletes the rows before it writes

sql_replace empties the table, then inserts the new rows, so:

  • A call with 0 rows leaves the table empty, and returns the number of rows it deleted as rows_affected.
  • A call the server rejects after emptying the table, such as one with a column the table does not have or a value of the wrong type, returns the error and leaves the table empty, e.g: {'error': "... Column not found in table '<table>': <column>"}.
  • A PersistEngine="HISTORICAL" suffix fails, so sql_replace cannot create a historical table.

Check that the data's columns match the table before calling it. Data that cannot be sent at all, such as columns of unequal length, raises before the table is touched.

To load a historical table, create it yourself, then insert:

client.sql("N1", 'CREATE PUBLIC TABLE HistTrades (sym String, px Double) USE PersistEngine="HISTORICAL"')
client.sql_insert("N1", "HistTrades", {"sym": ["IBM"], "px": [183.5]})

Data that does not upload as expected

  • Empty data writes nothing: sql_insert and sql_bulk_insert return {} for columns with no rows; sql_replace empties the table.
  • DataFrame values change type: a missing string is stored as "", a missing float as 0.0, and a datetime column becomes a String column, with values such as 2026-01-02 00:00:00.
  • int8 values wrap: a numpy int8 column becomes a Byte column, and a value of -1 is stored as 255.
  • datetime64 arrays are refused: the call fails with Column '<name>' must be a list or ndarray, so convert them to integers first.

Subscribing to live updates

subscribe(cluster, tables, sync=False) delivers each table's current rows, then every change, to on_update. unsubscribe(cluster, tables, sync=False) stops them.

rows = {}

class Listener:
    def on_update(self, client, name, update):
        if update.action == 3:
            rows.pop(update.id, None)
        else:
            rows.setdefault(update.id, {}).update(zip(update.field_names, update.row_data))

client.add_listener(Listener())
client.subscribe("N1", ["Quotes"], sync=True)

Check that rows holds the table's rows once on_update has run for each of them.

  • Updates merge by id: an update carries only the changed columns, and a delete carries none.
  • The update is a copy: its values stay valid after the callback returns.
  • on_disconnect fires for the Center connection only.
  • sync=True does not wait for the rows: it returns once the server has answered, before the rows have all reached on_update.
  • A subscription takes table names only: filters and column lists are C++ only.

How updates arrive is described in Live updates.

A mistyped table name is not reported

Subscribing to a table that does not exist reports success through on_subscribe and delivers nothing. Check the name with SELECT TableName FROM __TABLE.

Publishing objects

publish(cluster, type, id, fields, seqnum=0, expires_on_ms=0) sends one object to the Relay. The type names the table, and the id identifies the row.

1
2
3
4
client.publish("N1", "Orders", "ord-1", {"sym": "IBM", "qty": 100})
client.publish_batch("N1", "Orders", [("ord-2", {"sym": "AAPL", "qty": 5}),
                                      ("ord-3", {"sym": "MSFT", "qty": 7})])
client.remove("N1", "ord-1", "Orders")
  • fields: a dictionary or a list of (name, value) pairs. A bool is sent as 1 or 0 and stored as a Long.
  • publish_batch: takes a list of (id, fields) pairs, a list of dictionaries each with an "id" key, a dictionary of {id: fields}, or a DataFrame. DataFrame rows are published with no id, so each row is a new row and the table has no I column.
  • remove(cluster, id, type): deletes the object. The id comes before the type.

The target table must suit the object. A new type creates its table; an existing table needs an I column and a column for every field. See Publishing and the acknowledgement.

Checking what happened to a published object

The publish calls return None. The Relay's reply arrives in on_message_received, with status 0 when the Relay accepted the message:

on_message_received: status 0, "OK, object accepted"

Against a Relay running on Windows, the reply arrives instead in on_log, as a warning that starts Received message with unknown type:, because the Relay ends each message with a carriage return. Set Options.UNIX_MODE on the Relay connection when the server may run on Windows, and the replies reach on_message_received:

1
2
3
from pyami.rt.ami_client import Options

relay_config = AmiPublicationConfig("3289", True, "my_app", int(Options.UNIX_MODE))

Without the option, S=0 in the logged reply means accepted:

Received message with unknown type: M@1794407957169|Q=1|S=0|M="OK, object accepted"

Acceptance does not show that the row was stored: query the table to confirm it.

Leave expires_on_ms at 0

publish takes expires_on_ms. A time in the future stops the object being stored at all, and a time in the past is ignored.

A publish to a cluster name the client does not have is dropped, and logged to on_log as an error: Failed to send message: Cluster not found [<name>]. The same applies to register_command.

Registering commands

A command adds an action to the right-click menu of a real-time table panel in the Web. When a user runs it, the client calls on_command, and the program answers with send_command_response. Register it on the Relay connection.

from pyami.rt.ami_client import AmiClientCommandDef

class Listener:
    def on_command(self, client, name, request_id, cmd, user_name, object_type, object_id, params):
        client.send_command_response("N1", request_id, 0, "done")

restart = AmiClientCommandDef("restart_feed")
restart.set_name("Restart feed")
restart.set_help("Restarts the market data feed")
client.register_command("N1", restart)

Check that SELECT ID FROM __COMMAND lists restart_feed once the Relay replies OK, command accepted.

  • A command lasts as long as the connection: it is removed when the client disconnects, so register it again after a reconnect.
  • Level 0 is never registered: set_level(0) is acknowledged, but the command does not appear. Leave the level unset; the server then stores level 1.

What a command call receives

A user selects rows in a real-time table panel, right-clicks, and runs the command. A command with help text shows it first, with a "Submit" button. The Web then waits for the program's reply and shows its message, done in the example above.

on_command receives:

Argument Value
request_id Identifies this call; pass it to send_command_response
cmd The command id
user_name The Web user who ran the command
object_type The selected row's table; empty for a command that takes several rows
object_id The selected row's I value; empty for a command that takes several rows
params A dict of strings: S, the Web session id, and o, the row's internal id. For a command that takes several rows, V replaces o
  • A command takes one row by default: run with several rows selected, it receives only one of them.
  • set_select_mode(min, max) takes several rows: with set_select_mode(1, 10), params["V"] is a JSON list with one entry per selected row, e.g: [{"O":"o2","o":37000370},{"O":"o3","o":37000371}], where O is the row's I value.
  • set_where_clause limits the rows: with set_where_clause("qty > 5"), the command appears in the menu only when the selected rows match.
  • Against a Relay on Windows, set UNIX_MODE: without it, the call is logged to on_log as Received message with unknown type: E@..., on_command is not called, and the Web waits for a reply. See Checking what happened to a published object.

Disconnecting

remove_cluster(cluster, sync=False) closes the cluster's connections:

client.remove_cluster("N1", sync=True)

Check that the program then exits normally.

What this does not support

  • Filtering or projecting a subscription: the Python client subscribes by table name only, and has no get_table_schema.
  • Grouping statements in a transaction: every statement commits on its own.
  • Awaiting calls with asyncio: asynchronous calls take callbacks, which run on the client's callback thread.
  • Running on Python other than 3.14, or on macOS: the package ships compiled modules for CPython 3.14 on 64-bit Windows and 64-bit Linux with glibc 2.34 or later. On any other platform, pip install pyami-3forge installs an old 1.5.3 release instead, which this page does not describe.