# Adding a New Plot

When implementing your strategy or exchange classes, you may need to track and visualize various parameters over time. The `PlotData` object, initiated in the `BaseExchange` class, provides a flexible and powerful way to define and manage custom plots.

The `PlotData` object allows you to create multiple time series plots grouped under unique topics. These plots can include both line charts and scatter plots, enabling visualization of diverse data types, such as order locations, performance metrics, and price trends.

Plots created using the `PlotData` object can be retrieved programmatically via the [Plot Topics](/v1/apis/quickstart-5.md) API or viewed interactively in the **ATS Trading UI**, making them accessible for analysis and debugging.

## Accessing the `PlotData` Object

The `PlotData` object is initiated within the `BaseExchange` class. To access it, use the `exchange.get_plot_data()` method:

```python
plot_data = exchange.get_plot_data()
```

This ensures the `PlotData` object is used in the context of the exchange, maintaining consistency and access to pre-defined topics.

## Defining a Plot

Before recording data points, you must define a plot by setting a topic. A topic acts as a unique key for grouping related time series data. Each topic must have a unique name.

#### Parameters for Defining a Plot

* **`topic`**: A unique string identifying the topic of the plot.
* **`color`**: Color of the plot in hexadecimal (e.g., `#FF5733`).
* **`lines_or_markers`**:
  * `"lines"`: Creates a line plot.
  * `"markers"`: Creates a scatter plot.
* **`pattern`**:
  * Supported patterns for scatter plots: `"circle"`, `"triangle-up"`, `"triangle-down"`.
  * Supported patterns for line plots: `"dashdot"`, `"dash"`, `"dot"`, `"solid"`.

#### Example: Defining a Plot

```python
plot_data.set_topic(
    topic="My Custom Metric",
    color="#3498db",
    lines_or_markers="lines",
    pattern="dash"
)
```

## Recording Data Points

After defining a topic, you can record data points using the `add()` method. Each data point consists of:

* **`topic`**: The topic under which the data is grouped.
* **`time`**: The timestamp for the data point (must be a `datetime` object).
* **`num`**: The numeric value of the data point.
* **`label`** (optional): A string label displayed for marker plots when hovered over.

#### Example: Recording a Data Point

```python
from datetime import datetime

plot_data.add(
    topic="My Custom Metric",
    time=datetime.now(),
    num=42,
    label="Custom Label"
)
```

## Plotting Topics

The `plot_topics()` method allows you to visualize defined topics. You can create multiple subplots, specify rows and columns, and compress the graph to reduce resolution for large datasets.

#### Parameters for Plotting

* **`plots`**: A list of dictionaries specifying the topic and its subplot location:

  ```python
  plots = [
      {"topic": "My Custom Metric", "row": 1, "col": 1},
      {"topic": "Another Metric", "row": 1, "col": 2}
  ]
  ```
* **`rows`**: Total number of rows in the grid layout.
* **`cols`**: Total number of columns in the grid layout.
* **`length`**: Length of the time window to display (default is the full dataset).
* **`plot_compressed`**: If `True`, compresses the graph to reduce the number of data points.
* **`plot_compressed_size`**: The resolution of the compressed plot in data points.

#### Example: Plotting Topics

```python
fig = plot_data.plot_topics(
    plots=[
        {"topic": "My Custom Metric", "row": 1, "col": 1}
    ],
    rows=1,
    cols=1
)
fig.show()
```

## Managing Topics

#### Check If a Topic Exists

```python
if plot_data.is_topic_exist("My Custom Metric"):
    print("Topic exists!")
```

#### List All Topics

```python
topics = plot_data.get_topics()
print("Available topics:", topics)
```

## Example Use Case

#### Defining and Visualizing a Custom Plot

```python
# Access PlotData object
plot_data = exchange.get_plot_data()

# Define a custom plot
plot_data.set_topic(
    topic="Trade Volume",
    color="#e74c3c",
    lines_or_markers="markers",
    pattern="circle"
)

# Add data points
from datetime import datetime
plot_data.add(topic="Trade Volume", time=datetime.now(), num=150, label="Order ID: 123")

# Plot the topic
fig = plot_data.plot_topics(
    plots=[{"topic": "Trade Volume", "row": 1, "col": 1}],
    rows=1,
    cols=1
)
fig.show()
```

## Summary

The `PlotData` object offers robust functionality for defining, recording, and visualizing time series data. By leveraging its flexible API, you can easily track and display various parameters in your trading strategies and exchanges.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ats-doc.gitbook.io/v1/customizations/adding-a-new-plot.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
