Available languages: [Python](https://databento.com/docs/examples/basics-historical/programmatic-batch-download.python.md) · [C++](https://databento.com/docs/examples/basics-historical/programmatic-batch-download.cpp.md) · [Rust](https://databento.com/docs/examples/basics-historical/programmatic-batch-download.rust.md) · [HTTP](https://databento.com/docs/examples/basics-historical/programmatic-batch-download.http.md) · [Raw](https://databento.com/docs/examples/basics-historical/programmatic-batch-download.raw.md)

Source: https://databento.com/docs/examples/basics-historical/programmatic-batch-download


# Programmatic batch downloads

## Overview

In this example we will use the [Historical client](https://databento.com/docs/api-historical/client.md) to submit a batch request and download files programmatically.
To do this we will request five days of trade data, wait for our request to process, and then download the files locally and load them with a [DbnStore](https://databento.com/docs/api-historical/helpers/dbn-store.md) object.

> **See also**
>
> [Streaming vs. batch download](https://databento.com/docs/faqs/streaming-vs-batch-download.md).

## Example

```cpp
#include <chrono>
#include <databento/constants.hpp>
#include <databento/historical.hpp>
#include <databento/log.hpp>
#include <iostream>
#include <thread>

namespace db = databento;

int main() {
  auto client = db::Historical::Builder().SetKey("$YOUR_API_KEY").Build();
  db::BatchJob new_job = client.BatchSubmitJob(
      db::dataset::kGlbxMdp3, {"OZN.OPT"}, db::Schema::Trades,
      {"2022-12-12T00:00", "2022-12-12T08:00"}, {}, db::Compression::Zstd, {},
      {}, {}, {}, db::SplitDuration::Day, {}, db::Delivery::Download,
      db::SType::Parent, db::SType::InstrumentId, {});

  while (true) {
    db::BatchJob job_details = client.BatchGetJobDetails(new_job.id);
    if (job_details.state == db::JobState::Done) {
      break;
    }
    std::this_thread::sleep_for(std::chrono::seconds{1});
  }
  auto downloaded_files = client.BatchDownload(".", new_job.id);
  for (const auto& file : downloaded_files) {
    if (file.stem().extension() == ".dbn") {
      db::DbnStore dbn_store{file};
      std::size_t count = 0;
      dbn_store.Replay([&count](const db::Record&) {
        ++count;
        return db::KeepGoing::Continue;
      });
      std::cout << file << " contains " << count << " records\n";
    }
  }
  return 0;
}
```
## Result

```plaintext
./GLBX-20250116-9YULLS4UJH/glbx-mdp3-20221212.trades.dbn.zst contains 1662 records
./GLBX-20250116-9YULLS4UJH/glbx-mdp3-20221213.trades.dbn.zst contains 3511 records
./GLBX-20250116-9YULLS4UJH/glbx-mdp3-20221214.trades.dbn.zst contains 2544 records
./GLBX-20250116-9YULLS4UJH/glbx-mdp3-20221215.trades.dbn.zst contains 2460 records
./GLBX-20250116-9YULLS4UJH/glbx-mdp3-20221216.trades.dbn.zst contains 2191 records
```


# Programmatic batch downloads

## Overview

In this example we will use the [Historical client](https://databento.com/docs/api-historical/client.md) to submit a batch request and download files programmatically. To do this we will request five days of trade data, wait for our request to process, and then download the files locally and load them into a [DBNStore](https://databento.com/docs/api-historical/helpers/dbn-store.md) object.

> **See also**
>
> [Streaming vs. batch download](https://databento.com/docs/faqs/streaming-vs-batch-download.md).

## Example

```python
import pathlib
import time
import databento as db

# First, create a historical client
client = db.Historical("$YOUR_API_KEY")

# Next, we will submit a batch job
new_job = client.batch.submit_job(
    dataset="GLBX.MDP3",
    start="2022-12-12T00:00:00",
    end="2022-12-17T00:00:00",
    symbols="OZN.OPT",
    schema="trades",
    split_duration="day",
    stype_in="parent",
)

# Retrieve the new job ID
new_job_id: str = new_job["id"]

# Now, we have to wait for our batch job to complete
while True:
    job_details = client.batch.get_job_details(new_job_id)
    if job_details["state"] == "done":
        break  # Exit the loop to continue
    time.sleep(1.0)

# Once complete, we will download the files
downloaded_files = client.batch.download(
    job_id=new_job_id,
    output_dir=pathlib.Path.cwd(),
)

# Finally, we can load the data into a DBNStore for analysis
for file in sorted(downloaded_files):
    if file.name.endswith(".dbn.zst"):
        data = db.DBNStore.from_file(file)

        # Convert the data to a pandas.DataFrame
        df = data.to_df()
        print(f"{file.name} contains {len(df):,d} records")
```
## Result

```plaintext
glbx-mdp3-20221212.trades.dbn.zst contains 2,055 records
glbx-mdp3-20221213.trades.dbn.zst contains 4,112 records
glbx-mdp3-20221214.trades.dbn.zst contains 2,936 records
glbx-mdp3-20221215.trades.dbn.zst contains 3,034 records
glbx-mdp3-20221216.trades.dbn.zst contains 2,540 records
```


# Programmatic batch downloads

## Overview
In this example we will use the [Historical client](https://databento.com/docs/api-historical/client.md) to submit a batch request and download files programmatically.
To do this we will request five days of trade data, wait for our request to process, and then download the files locally and load them with a `AsyncDbnDecoder` object.

> **See also**
>
> [Streaming vs. batch download](https://databento.com/docs/faqs/streaming-vs-batch-download.md).

## Example
```rust
use std::time::Duration;

use databento::{
    HistoricalClient,
    dbn::{Dataset::GlbxMdp3, SType, Schema, decode::AsyncDynReader},
    historical::{
        batch::{DownloadParams, JobState, SubmitJobParams},
        timeseries::AsyncDbnDecoder,
    },
};
use time::macros::datetime;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut client = HistoricalClient::builder().key_from_env()?.build()?;
    let job = client
        .batch()
        .submit_job(
            &SubmitJobParams::builder()
                .dataset(GlbxMdp3)
                .date_time_range(datetime!(2022-10-12 00:00 UTC)..datetime!(2022-10-17 00:00 UTC))
                .symbols("OZN.OPT")
                .stype_in(SType::Parent)
                .schema(Schema::Trades)
                .build(),
        )
        .await?;
    // Now we wait for the job to complete
    loop {
        let job_details = client.batch().get_job_details(&job.id).await?;
        if job_details.state == JobState::Done {
            break;
        }
        tokio::time::sleep(Duration::from_secs(1)).await;
    }
    // Once complete, we download the files
    let mut downloaded_files = client
        .batch()
        .download(
            &DownloadParams::builder()
                .output_dir(std::env::current_dir()?)
                .job_id(job.id)
                .build(),
        )
        .await?;
    downloaded_files.sort();
    for downloaded_file in downloaded_files {
        let Some(file_name) = downloaded_file.file_name().and_then(|name| name.to_str()) else {
            continue;
        };
        if file_name.ends_with(".dbn") || file_name.ends_with(".dbn.zst") {
            // `DynReader` infers the compression (zstd or uncompressed) from the file
            let mut decoder =
                AsyncDbnDecoder::new(AsyncDynReader::from_file(&downloaded_file).await?).await?;
            let mut count = 0;
            while decoder.decode_record_ref().await?.is_some() {
                count += 1;
            }
            println!("{file_name} contains {count} records");
        }
    }

    Ok(())
}
```
## Result
```plaintext
glbx-mdp3-20221012.trades.dbn.zst contains 3041 records
glbx-mdp3-20221013.trades.dbn.zst contains 7956 records
glbx-mdp3-20221014.trades.dbn.zst contains 3956 records
glbx-mdp3-20221016.trades.dbn.zst contains 54 records
```
