Skip to content

Python Examples

The Python examples use virtufin-api, which reaches every service through the gateway: state and pub/sub directly, WorkManager as client.gateway.workmanager.<Method>(...). A WebSocket connection is a WebSocketFeed worker that WorkManager runs; python/websocket_feed.py wraps its calls.

Service SDK

Package Registry Install
virtufin-api Gitea PyPI pip install virtufin-api --index-url ...

Connecting: the context

Each example sets CONTEXT_NAME near its top, "demo" by default: a name in ~/.config/virtufin/api/contexts.toml (see Getting Started). python/virtufin_context.py reads the entry and builds the client:

from virtufin_context import api_client, describe, load_context

CONTEXT_NAME = "demo"  # or "local" for a deploy-local backend

context = load_context(CONTEXT_NAME)
print(describe(context))  # context demo: api.virtufin.com:443 tls=True key=set
api = api_client(context)  # ApiClient(host, grpc_port, tls, api_key)

Key Patterns

# State: the service must be one the gateway registers ("statestore" on demo and local).
await api.save_state_async("statestore", "my-key", json.dumps(data))
data = json.loads((await api.get_state_async("statestore", "my-key"))["value"])

# WebSocketFeed workers that serve topics (python/websocket_feed.py): market-data-devkit's
# feeds.resolve plans the feeds for the topics (venue preset, limits, deterministic names),
# feeds.apply creates them or serves running ones their topics, then each `status` until
# connected. On demo, always remove them (in `finally`): close_feeds deletes the owner's feeds.
from websocket_feed import close_feeds, feed_command, serve_topics

topic = "act.exchange.binance.orderbook.update.BTC_USDT"   # build it with virtufin_naming
feeds = await serve_topics(api, [topic], owner="my-script")
try:
    status = await feed_command(api, feeds[0].worker_id, "status")  # InvokeWorkerCommand
finally:
    await close_feeds(api, "my-script")

# Pub/sub
async for event in api.pubsub.subscribe_async_iter(topic="my-topic"):
    payload = json.loads(event.data_as_text())

Dependencies

virtufin-api
python-dotenv
grpcio