Available languages: [Python](https://databento.com/docs/examples/basics-live/live-stream-to-file.python.md) · [C++](https://databento.com/docs/examples/basics-live/live-stream-to-file.cpp.md) · [Rust](https://databento.com/docs/examples/basics-live/live-stream-to-file.rust.md) · [HTTP](https://databento.com/docs/examples/basics-live/live-stream-to-file.http.md) · [Raw](https://databento.com/docs/examples/basics-live/live-stream-to-file.raw.md)

Source: https://databento.com/docs/examples/basics-live/live-stream-to-file


# Stream live data to a file

## Overview

In this example we will use the [LiveBlocking client](https://databento.com/docs/api-live/client/live-blocking.md) to save live data to a file using an [output stream](https://databento.com/docs/api-live/client/add-stream.md). We will then open this file as a [DBNStore](https://databento.com/docs/api-historical/helpers/dbn-store.md). This allows for live data to be archived for replay and testing purposes.

## Databento Binary Encoding (DBN)

The binary data will be written to the stream in the [DBN](https://databento.com/docs/conventions/databento-binary-encoding.md) format.
This is a zero-copy format that is extremely fast and efficient on bandwidth.
The easiest way to read data encoded in DBN is through our client libraries or the [dbn-cli](https://crates.io/crates/dbn-cli) tool.

## Example

```cpp
#include <chrono>
#include <databento/dbn.hpp>
#include <databento/dbn_encoder.hpp>
#include <databento/dbn_store.hpp>
#include <databento/file_stream.hpp>  // OutFileStream
#include <databento/live.hpp>         // LiveBuilder
#include <databento/pretty.hpp>
#include <databento/publishers.hpp>  // Dataset
#include <databento/record.hpp>      // Record
#include <databento/symbol_map.hpp>  // PitSymbolMap
#include <iomanip>
#include <iostream>

namespace db = databento;

int main() {
  auto client = db::LiveBlocking::Builder()
                    .SetKey("$YOUR_API_KEY")
                    .SetDataset(db::Dataset::GlbxMdp3)
                    .BuildBlocking();
  // First, we subscribe to the OHLCV-1s schema for a few symbols
  client.Subscribe({"ES.c.0", "ES.c.1", "CL.c.0", "CL.c.1"},
                   db::Schema::Ohlcv1S, db::SType::Continuous);
  // We start streaming
  db::Metadata metadata = client.Start();
  {
    // We open a file for writing and encode the metadata
    db::OutFileStream out_file{"example.dbn"};
    db::DbnEncoder encoder{metadata, &out_file};
    // Wait for at least one record and 5 seconds before closing the connection
    const std::chrono::seconds timeout{5};
    const auto start = std::chrono::steady_clock::now();
    while (auto* record = client.NextRecord(timeout)) {
      encoder.EncodeRecord(*record);
      if (std::chrono::steady_clock::now() - start >= timeout) {
        break;
      }
    }
  }
  // Finally, we open the DBN file
  db::DbnStore store{"example.dbn"};
  std::cout << std::left << std::setw(32) << "ts_event" << std::right
            << std::setw(16) << "instrument_id" << std::setw(12) << "open"
            << std::setw(12) << "high" << std::setw(12) << "low"
            << std::setw(12) << "close" << std::setw(10) << "volume" << "  "
            << "symbol\n";
  db::PitSymbolMap symbol_map;
  while (auto* record = store.NextRecord()) {
    symbol_map.OnRecord(*record);
    if (auto* ohlcv = record->GetIf<db::OhlcvMsg>()) {
      std::cout << std::left << std::setw(32)
                << db::pretty::Ts{ohlcv->hd.ts_event} << std::right
                << std::setw(16) << ohlcv->hd.instrument_id
                << std::setprecision(2) << std::setw(12)
                << db::pretty::Px{ohlcv->open} << std::setw(12)
                << db::pretty::Px{ohlcv->high} << std::setw(12)
                << db::pretty::Px{ohlcv->low} << std::setw(12)
                << db::pretty::Px{ohlcv->close} << std::setw(10)
                << ohlcv->volume << "  " << symbol_map.At(*ohlcv) << '\n';
    }
  }
  return 0;
}
```
## Result

```plaintext
ts_event                           instrument_id        open        high         low       close    volume  symbol
2026-04-20T16:27:46.000000000Z          42140864     7137.25     7137.25     7137.00     7137.00        57  ESM6
2026-04-20T16:27:47.000000000Z            670557       87.22       87.22       87.22       87.22         3  CLM6
2026-04-20T16:27:48.000000000Z            670557       87.23       87.23       87.22       87.22         3  CLM6
2026-04-20T16:27:48.000000000Z          42140864     7137.00     7137.00     7137.00     7137.00         2  ESM6
2026-04-20T16:27:49.000000000Z          42140864     7137.00     7137.00     7137.00     7137.00        23  ESM6
2026-04-20T16:27:50.000000000Z            670557       87.23       87.23       87.21       87.22         5  CLM6
2026-04-20T16:27:50.000000000Z          42140864     7137.00     7137.00     7137.00     7137.00         1  ESM6
2026-04-20T16:27:51.000000000Z            670557       87.21       87.21       87.21       87.21         1  CLM6
```


# Stream live data to a file

## Overview

In this example we will use the [Live client](https://databento.com/docs/api-live/client/live.md) to save live data to a file using an [output stream](https://databento.com/docs/api-live/client/add-stream.md). We will then open this file as a [DBNStore](https://databento.com/docs/api-historical/helpers/dbn-store.md). This allows for live data to be archived for replay and testing purposes.

## Databento Binary Encoding (DBN)

The binary data will be written to the stream in the [DBN](https://databento.com/docs/conventions/databento-binary-encoding.md) format. This is a zero-copy format
that is extremely fast and efficient on bandwidth. The easiest way to read data
encoded in DBN is through our client libraries or the [dbn-cli](https://crates.io/crates/dbn-cli) tool.

## Example

```python
import databento as db

# First, create a live client and connect
live_client = db.Live(key="$YOUR_API_KEY")

# Next, we will subscribe to the OHLCV-1s schema for a few symbols
live_client.subscribe(
    dataset="GLBX.MDP3",
    schema="ohlcv-1s",
    stype_in="continuous",
    symbols=["ES.c.0", "ES.c.1", "CL.c.0", "CL.c.1"],
)

# Now, we will open a file for writing and start streaming
live_client.add_stream("example.dbn")
live_client.start()

# We will listen for 10 seconds before closing the connection
# Any ohlcv-1s bars received during this time will be saved
live_client.block_for_close(timeout=10)

# Finally, we will open the DBN file
dbn_store = db.DBNStore.from_file("example.dbn")
print(dbn_store.to_df(schema="ohlcv-1s"))
```
## Result

```plaintext
                           rtype  publisher_id  instrument_id     open     high      low    close  volume symbol
ts_event
2023-12-18 14:40:19+00:00     32             1          17077  4785.75  4785.75  4785.75  4785.75     143   ESH4
2023-12-18 14:40:19+00:00     32             1         686071    74.19    74.19    74.19    74.19       6   CLG4
2023-12-18 14:40:20+00:00     32             1          17077  4785.75  4785.75  4785.50  4785.75       8   ESH4
2023-12-18 14:40:20+00:00     32             1         686071    74.19    74.20    74.19    74.20       6   CLG4
2023-12-18 14:40:21+00:00     32             1          17077  4785.75  4785.75  4785.75  4785.75     105   ESH4
2023-12-18 14:40:21+00:00     32             1         686071    74.20    74.21    74.20    74.21       8   CLG4
```


# Stream live data to a file

## Overview

In this example we will use the [Live client](https://databento.com/docs/api-live/client/live.md) to save live data to a file using an [output stream](https://databento.com/docs/api-live/client/add-stream.md). We will then open this file as a [DBNStore](https://databento.com/docs/api-historical/helpers/dbn-store.md). This allows for live data to be archived for replay and testing purposes.

## Databento Binary Encoding (DBN)

The binary data will be written to the stream in the [DBN](https://databento.com/docs/conventions/databento-binary-encoding.md) format.
This is a zero-copy format that is extremely fast and efficient on bandwidth.
The easiest way to read data encoded in DBN is through our client libraries or the [dbn-cli](https://crates.io/crates/dbn-cli) tool.

## Example

```rust
use std::time::Instant;

use databento::{
    LiveClient,
    dbn::{
        Dataset::GlbxMdp3,
        OhlcvMsg, PitSymbolMap, SType, Schema,
        decode::AsyncDbnDecoder,
        encode::{AsyncDbnEncoder, AsyncEncodeRecord, AsyncEncodeRecordRef},
        pretty::{Px, Ts},
    },
    live::Subscription,
};
use tokio::{fs::File, io::BufWriter};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut client = LiveClient::builder()
        .key_from_env()?
        .dataset(GlbxMdp3)
        .build()
        .await?;
    // First, we subscribe to the OHLCV-1s schema for a few symbols
    client
        .subscribe(
            Subscription::builder()
                .schema(Schema::Ohlcv1S)
                .symbols(vec!["ES.c.0", "ES.c.1", "CL.c.0", "CL.c.1"])
                .stype_in(SType::Continuous)
                .build(),
        )
        .await?;
    // We start streaming
    let metadata = client.start().await?;
    // We open a file for writing and encode the metadata
    let mut encoder = AsyncDbnEncoder::new(
        BufWriter::new(File::create("example.dbn").await?),
        &metadata,
    )
    .await?;
    // Wait for at least one record and 5 seconds before closing the connection
    let now = Instant::now();
    while let Some(record) = client.next_record().await? {
        encoder.encode_record_ref(record).await?;
        if now.elapsed().as_secs() >= 5 {
            break;
        }
    }
    // Next, we shutdown the encoder to ensure any buffered output
    // is written to the file
    encoder.shutdown().await?;

    // Finally, we open the DBN file
    let mut dbn_file = AsyncDbnDecoder::new(File::open("example.dbn").await?).await?;
    let mut symbol_map = PitSymbolMap::new();
    println!(
        "{:<32}{:>13}{:>11}{:>11}{:>11}{:>11}{:>8}  symbol",
        "ts_event", "instrument_id", "open", "high", "low", "close", "volume"
    );
    while let Some(record) = dbn_file.decode_record_ref().await? {
        symbol_map.on_record(record)?;
        if let Some(ohlcv) = record.get::<OhlcvMsg>() {
            let symbol = &symbol_map[ohlcv];
            println!(
                "{:<32}{:>13}{:>11.4}{:>11.4}{:>11.4}{:>11.4}{:>8}  {symbol}",
                Ts(ohlcv.hd.ts_event),
                ohlcv.hd.instrument_id,
                Px(ohlcv.open),
                Px(ohlcv.high),
                Px(ohlcv.low),
                Px(ohlcv.close),
                ohlcv.volume
            );
        }
    }
    Ok(())
}
```
## Result

```plaintext
ts_event                        instrument_id       open       high        low      close  volume  symbol
2025-06-29T22:00:00.000000000Z          14160  6223.2500  6228.2500  6223.2500  6224.7500     282  ESU5
2025-06-29T22:00:00.000000000Z          48059    63.7500    63.7800    63.7000    63.7100       9  CLU5
2025-06-29T22:00:00.000000000Z         209884    65.1500    65.1800    65.0800    65.1000      44  CLQ5
2025-06-29T22:00:01.000000000Z          14160  6224.5000  6225.5000  6224.5000  6225.0000      48  ESU5
2025-06-29T22:00:01.000000000Z         209884    65.0900    65.0900    65.0900    65.0900       1  CLQ5
2025-06-29T22:00:01.000000000Z          48059    63.6800    63.6800    63.6700    63.6700       3  CLU5
2025-06-29T22:00:02.000000000Z          14160  6224.5000  6225.5000  6224.2500  6224.7500      24  ESU5
2025-06-29T22:00:02.000000000Z         209884    65.0900    65.0900    65.0600    65.0900      14  CLQ5
2025-06-29T22:00:03.000000000Z          14160  6224.5000  6225.7500  6224.5000  6225.7500      24  ESU5
2025-06-29T22:00:03.000000000Z         209884    65.1000    65.1200    65.0700    65.0700       3  CLQ5
```
