Introduction
AIS (Automatic Identification System) is a maritime tracking technology that lets vessels broadcast their position and voyage information. The Vessel Tracking API makes this AIS data available for integration into custom applications and workflows, both as historical records and as near real-time updates.
In Visualizing Historical Vessel Positions on a World Map with the Vessel Tracking API and Python (Part 1), we used the REST API to download a vessel's recent position history and replay its route on a map. Replaying the past is useful for analysis, but many monitoring scenarios need to know where a vessel is right now. You could keep asking the REST API for the latest position, but you would have to guess how often to ask.
The Vessel Tracking API also provides a WebSocket interface. You open one connection, tell the service which vessels you care about, and the service pushes a message each time one of them reports a new position. In this article, we'll connect to that interface, subscribe to a vessel, and draw its positions on a world map as they arrive.
Note: This is Part 2 of a two-part series. You do not need to have completed Part 1 to follow along, but it explains the AIS data and the REST endpoints that we build on here.
What We'll Build
We'll build a Jupyter notebook that connects to the Vessel Tracking API's WebSocket interface, subscribes to a vessel, and shows its positions on a map as they are reported.
The final output looks similar to the animation below. The world map shows where the vessel is, while the close-up map follows it and draws its path as each new position arrives. The status line above the maps shows how many positions have been received and when the last message arrived.
The animation is sped up 64x to make the movement easy to see. In practice, a new position arrives only when the vessel reports one, which can be minutes apart.
The notebook:
- authenticates with the streaming service and connects to it
- subscribes to a vessel and keeps the connection alive
- receives position updates as they are reported
- shows the vessel's latest position, and the path it has followed since you started, on a world map and on a zoomed-in close-up map
Why Stream Vessel Positions?
Live vessel positions are commonly used for:
- fleet monitoring
- port and terminal operations
- arrival and departure awareness
- supply chain monitoring
- operational dashboards and alerts
With REST you ask for data whenever you need it. With WebSocket streaming the service sends it to you:
| REST API (Part 1) | WebSocket streaming (this article) | |
|---|---|---|
| Who starts each update | Your code asks | The service sends |
| Best for | History, snapshots, reports | Live maps, alerts, dashboards |
| Connection | A new request each time | One long-lived connection |
Vessels report their positions through AIS, so an update arrives when a vessel transmits and updates can be minutes apart. In our testing the first update after subscribing took a couple of minutes, and each position was already several minutes old when it reached us. Treat the stream as near real time, not as continuous GPS tracking.
Prerequisites
Before getting started, make sure you have the following:
- Python 3.10 or later
- A Python environment with the Jupyter Notebook extension (VS Code) or JupyterLab, and these libraries installed:
- websockets==16.1.1
- ipyleaflet==0.20.0
We use ipyleaflet to display the maps. The maps use OpenStreetMap tiles, so the notebook needs internet access for them. - ipywidgets==8.1.9
- A Vessel Tracking API key that is entitled to the vessel you want to watch
This tutorial assumes basic familiarity with Python and Jupyter notebooks.
If you don't already have a Vessel Tracking API key, contact your LSEG account representative or refer to the Vessel Tracking API documentation for instructions on generating one from the Vessel Tracking web application.
Store the full authorization value in a 'config.ini' file next to the notebook, and keep that file out of version control:
Solution Overview
In this example we'll use the Vessel Tracking API's WebSocket interface to receive vessel position updates, keep the latest position and path in Python, and draw them on maps with ipyleaflet. The overall workflow looks like this:
The final output is a world map and a close-up map that update while the notebook runs
How Vessel Tracking WebSocket Streaming Works
The service uses an API key and a single-use ticket (this differs from the OAuth login used by financial market-data WebSocket APIs). Connecting takes five steps, described in the Vessel Tracking API documentation.
1. Get a ticket. Send an HTTPS GET to /VesselTrackerWebSockets/auth with your API key in the Authorization header:
The reply contains three values: user, label and timestamp. A ticket can be used once and expires after ten minutes if unused.
2. Connect. Open a secure WebSocket and pass the ticket in the query string. Send the same Authorization header:
3. Subscribe. Once connected, send a JSON message that lists the vessels to watch. Use the ticket's label as the streamID:
type can be imo, ric or eni. origin is a label for your application: we use python-jupyter, and you should confirm with your LSEG representative whether your deployment expects a specific value.
4. Receive positions and stay connected. Each update arrives as JSON with fields such as latitude, longitude and timestampPosition. You must also send a keepalive message every 120 seconds, and again straight away if the server sends an expiryWarning:
5. Stop. Send unsubscribe with an empty vessels list to remove all subscriptions, then close the connection. To connect again, get a new ticket.
| Message | Sent by | When |
|---|---|---|
| subscribe | You | Right after connecting |
| position update | Server | Whenever a watched vessel reports a position |
| keepalive | You | Every 120 seconds |
| expiryWarning | Server | The connection is about to expire: reply with a keepalive at once |
| unsubscribe | You | Before closing |
The server does not send the vessel's current position when you subscribe, so the notebook also asks the REST API for the latest position to show something on the map straight away.
Let's work on this
Step 1 ) Import the libraries
Uncomment the %pip line once to install the libraries, and restart the kernel if asked. Everything else comes from Python's standard library.
Step 2) Configure the notebook
Set the service host, the vessel to watch (by IMO number) and the API key. The host is the one used in the REST examples of the Vessel Tracking API documentation; use the host of your own deployment if it differs. The default IMO is a vessel from the documentation's examples, so replace it with a vessel you are entitled to see.
A position is shown in gray when it is older than STALE_SECONDS, so you can tell a vessel that has gone quiet from one that is simply moving slowly.
Step 3) Get a ticket, build the messages and read the latest position
These small functions map directly to the steps above:
- get_ticket() calls the /auth endpoint (step 1).
- connect_url() builds the wss:// address from the ticket (step 2).
- subscribe_message(), keepalive_message() and unsubscribe_message() build the JSON messages (steps 3 to 5).
- get_latest_position() asks the REST API for the vessel's latest position. REST field names start with a capital letter, so we rename them to match the lower camel case names used by the stream.
The ticket URL contains a temporary credential, so never print it.
Step 4) Keep the latest position and the path
The notebook uses these fields from the position data. The stream spells field names in lower camel case (latitude), while the REST field list starts with a capital letter (Latitude). Not every field is guaranteed in every stream message, so update_position() keeps the values it already has.
| Field | Description |
|---|---|
| latitude / longitude | Position of the vessel |
| timestampPosition | When the position was reported (UTC) |
| imo / vesselName | Vessel identity |
| speedOverGround | Reported speed in knots |
| aisDestination | Destination reported through AIS |
| navigationalStatus | Operational status of the vessel |
- position holds the vessel's latest position and trail holds every distinct location received so far, which we will draw as a line.
- update_position() accepts a position from either the REST snapshot or the stream. It ignores updates that are older than the one we already have, or that have no usable coordinates, and adds new locations to the trail. Timestamps without a time zone are treated as UTC.
- handle_message() decodes one message from the stream and ignores anything that is not valid JSON. The server may send a list of positions or a single one, so we handle both. If the message is an expiryWarning we reply with a keepalive immediately, every message that carries coordinates is passed to update_position().
Step 5) Prepare the world map and the close-up map
This cell only creates the maps, step 7 displays them. A vessel moves only a fraction of a degree per hour, so one map cannot show both where it is in the world and how it is moving. We use two:
- The world map shows the whole world, so you see where the vessel is.
- The close-up map is zoomed in and recenters on the vessel at every refresh, so small changes in position are visible. Because it recenters, it cannot be panned while tracking runs.
On both maps a blue line shows where the vessel has been, small gray dots mark its earlier positions, and the large dot at the end is the latest position. That dot is red, or gray when the position is older than STALE_SECONDS. Click the dot on the world map to see the vessel's details.
- draw() creates the line and dots for one map the first time and updates them afterwards.
- render_map() runs once per second, so the notebook updates the maps in place instead of creating a new figure for each message.
Step 6) Stream the positions
stream() follows the steps from the introduction in a loop:
- Read the latest position from REST, so the map has something to show.
- Get a new ticket, because a ticket works only once.
- Connect and send the subscribe message.
- Start send_keepalives() in the background, then handle every message that arrives.
- When the loop ends, for example because you pressed stop, send unsubscribe and close the connection.
If the connection drops, stream() waits five seconds and starts again from step 1 in the loop above. Errors such as a rejected API key stop the stream and are shown in the status line. A production application would also add a growing delay between retries and monitoring.
- run_tracking() runs the stream and the map refresh together
- start_tracking() and stop_tracking() start and cancel that task.
Step 7) Start tracking and show the maps
Run the code below. It displays the status line, the world map and the close-up map, then returns immediately while positions stream in. The status line shows how many positions have arrived and the time of the last message from the server, so you can see that the stream is alive even while the vessel has not moved. The vessel appears as soon as the REST snapshot loads, and each streamed update extends its path. The first streamed update can take a couple of minutes, and a slow vessel moves only slightly between updates. Do not rerun the setup cells while tracking is running.
Step 8) Stop tracking
Run this cell when you want to stop. It cancels the stream, which sends unsubscribe and closes the WebSocket. The maps keep the path that has been drawn. Run step 7 to start again.
Step 9) Reset the maps
Run this cell after stopping to remove the path and start from a clean map. Saving a notebook does not keep the WebSocket connection open. Before sharing a notebook, clear any outputs that contain licensed vessel data.
Troubleshooting
| Symptom | What to check |
|---|---|
| KeyError: 'vessel_tracking' | config.ini is next to the notebook and has a [vessel_tracking] section with api_key. Start the kernel from the notebook's folder. |
| Status shows Stopped: HTTP Error 401 or 403 | The full authorization value ('apikey-v1 ...'), its validity and your entitlement. It is not an OAuth bearer token. |
| Stopped: HTTP Error 404 or a rejected handshake | The host and the exact paths for your deployment. |
| Connected but nothing moves | Wait, the first update can take a couple of minutes. Also check that you are entitled to the vessel and that it has reported a new position recently. |
| Dot is gray | The latest position is older than STALE_SECONDS. The status line shows its age. |
| Connection drops after a few minutes | The keepalive message must be sent every 120 seconds. WebSocket ping and pong frames do not replace it. |
| Blank map | Widget support in your notebook editor, the installed packages, and access to the OpenStreetMap tile servers. |
Potential Enhancements
This example intentionally focuses on a single vessel to keep the workflow easy to understand. The same approach can be extended to support:
- Fleet Tracking: Add more entries to the vessels list of the subscribe message to watch several vessels on the same map. Each vessel needs its own entitlement, and your LSEG representative can confirm the subscription limits.
- Geofencing: Highlight vessels that enter or leave a predefined area.
- Alerts: Notify users when a vessel stops reporting or arrives at a port.
- Data Storage: Save the positions you receive. The History endpoint used in Part 1 keeps only the most recent 24 hours.
- Resilience: Add a growing delay between reconnection attempts and monitor the connection.
- Operational Dashboards: Combine live positions with business workflows and analytics.
Source Code
The complete source code and Jupyter notebook used throughout this tutorial are available in the GitHub repository linked in the top-right corner of this page. You can use the notebook as a starting point and adapt it to watch different vessels or build more advanced maritime monitoring applications.
Conclusion
In this article, we demonstrated how the Vessel Tracking API's WebSocket interface delivers vessel positions as they are reported. Starting from an API key, we:
- requested a single-use ticket and connected to the streaming service
- subscribed to a vessel and kept the connection alive
- decoded the position messages and kept the latest position and path
- showed the vessel live on a world map and a close-up map
Together with Part 1, which replayed recent history, you can now both look back at where a vessel has been and watch where it is going as new positions are reported.
References
- Register or Log in to applaud this article
- Let the author know how much this article helped you
Get In Touch
Source Code
Related APIs
Related Articles
Request Free Trial
Call your local sales team
Americas
All countries (toll free): +1 800 427 7570
Brazil: +55 11 47009629
Argentina: +54 11 53546700
Chile: +56 2 24838932
Mexico: +52 55 80005740
Colombia: +57 1 4419404
Europe, Middle East, Africa
Europe: +442045302020
Africa: +27 11 775 3188
Middle East & North Africa: 800035704182
Asia Pacific (Sub-Regional)
Australia & Pacific Islands: +612 8066 2494
China mainland: +86 10 6627 1095
Hong Kong & Macau: +852 3077 5499
India, Bangladesh, Nepal, Maldives & Sri Lanka:
+91 22 6180 7525
Indonesia: +622150960350
Japan: +813 6743 6515
Korea: +822 3478 4303
Malaysia & Brunei: +603 7 724 0502
New Zealand: +64 9913 6203
Philippines: 180 089 094 050 (Globe) or
180 014 410 639 (PLDT)
Singapore and all non-listed ASEAN Countries:
+65 6415 5484
Taiwan: +886 2 7734 4677
Thailand & Laos: +662 844 9576