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

Source: https://databento.com/docs/examples/basics-live/live-tick-trin


# Calculate TICK and TRIN indicators

## Overview

In this example we will use the [LiveThreaded client](https://databento.com/docs/api-live/client/live-threaded.md) to calculate two technical indicators: market tick (TICK) and the traders index (TRIN).
To do this we will request trades for all symbols and calculate these indicators for every execution.

## Trades schema

These indicators are updated on every execution for all symbols on the venue.
To get this, we will use the [trades schema](https://databento.com/docs/schemas/trades.md), which provides records for every trade execution.

## Example

```cpp
#include <cmath>
#include <databento/constants.hpp>  // dataset
#include <databento/live.hpp>       // LiveBuilder
#include <databento/record.hpp>     // TradeMsg
#include <databento/symbology.hpp>  // kAllSymbols
#include <iomanip>
#include <iostream>

namespace db = databento;

class TickTrinCalculator {
 public:
  TickTrinCalculator() = default;

  db::KeepGoing HandleRecord(const db::Record& record) {
    if (const auto* trade = record.GetIf<db::TradeMsg>()) {
      if (trade->side == db::Side::Ask) {
        ++downtick_;
        downvol_ += trade->size;
      } else if (trade->side == db::Side::Bid) {
        ++uptick_;
        upvol_ += trade->size;
      }

      double tick =
          static_cast<double>(uptick_) / static_cast<double>(downtick_);
      double trin_base =
          static_cast<double>(upvol_) / static_cast<double>(downvol_);
      double trin = tick / trin_base;
      // Only print if one of the indicators is finite
      if (std::isfinite(tick) || std::isfinite(trin)) {
        std::cout << std::fixed << std::setprecision(4) << tick << ", " << trin
                  << '\n';

        ++measurements_count_;
        if (measurements_count_ == 20) {
          return db::KeepGoing::Stop;
        }
      }
    }
    return db::KeepGoing::Continue;
  }

 private:
  std::size_t measurements_count_{};
  std::uint32_t uptick_{};
  std::uint32_t downtick_{};
  std::uint32_t upvol_{};
  std::uint32_t downvol_{};
};

int main() {
  TickTrinCalculator calculator;
  auto client = db::LiveThreaded::Builder()
                    .SetKey("$YOUR_API_KEY")
                    .SetDataset(db::Dataset::GlbxMdp3)
                    .BuildThreaded();
  client.Subscribe({"CL.c.0"}, db::Schema::Trades, db::SType::Continuous);
  client.Start([&calculator](const db::Record& record) {
    return calculator.HandleRecord(record);
  });
  // Wait for callback to return `Stop`
  client.BlockForStop();

  return 0;
}
```
## Result

```plaintext
1.0000, 0.5000
2.0000, 0.6667
3.0000, 0.7500
4.0000, 0.6667
5.0000, 0.7143
2.5000, 1.0714
3.0000, 1.1250
3.5000, 1.1667
4.0000, 1.2000
4.5000, 1.2273
5.0000, 1.0000
5.0000, 1.0000
5.5000, 1.0312
6.0000, 1.0000
4.0000, 1.1111
3.0000, 1.5000
2.4000, 1.4667
2.6000, 1.5053
2.6000, 1.5053
2.6000, 1.5053
```


# Calculate TICK and TRIN indicators

## Overview

In this example we will use the [Live client](https://databento.com/docs/api-live/client/live.md) to calculate two technical indicators: market tick (TICK) and the traders index (TRIN).

## Trades schema

These indicators are updated on every execution for all symbols on the venue. To get
this, we will use the [trades schema](https://databento.com/docs/schemas/trades.md),
which provides records for every trade execution.

## Example

We can pass in `symbols="ALL_SYMBOLS"` to request all symbols of a dataset at
once.

```python
import databento as db
import numpy as np

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

# Next, we will subscribe to trades for all symbols
live_client.subscribe(
    dataset="GLBX.MDP3",
    schema="trades",
    symbols="ALL_SYMBOLS",
)

# Then, we setup our initial values for TICK/TRIN
uptick = downtick = upvol = downvol = 0

# We will consume 20 records and then close for this example
trades = 0
for record in live_client:
    if isinstance(record, db.TradeMsg):
        side = record.side
        if side == "A":
            downtick += 1
            downvol += record.size
        elif side == "B":
            uptick += 1
            upvol += record.size

        tick = uptick / downtick if downtick != 0 else np.nan
        trin_base = upvol / downvol if downvol != 0 else np.nan
        trin = tick / trin_base if trin_base != 0 else np.nan

        print(f"{tick:.4f}", f"{trin:.4f}")
        trades += 1
        if trades >= 20:
            break
    elif isinstance(record, db.ErrorMsg):
        print(f"Error: {record.err}")
```
## Result

```plaintext
1.0000 1.0000
0.5000 1.0000
0.3333 1.0000
0.2500 1.0000
0.2000 2.2000
0.1667 2.0000
0.1429 1.8571
0.1250 1.8750
0.1111 2.1111
0.2222 2.1111
0.3333 1.5833
0.4444 1.0556
0.4000 1.0000
0.5000 1.0000
0.6000 1.0909
0.5455 1.1405
0.5000 1.0909
0.4615 1.0909
0.4286 1.0909
```


# Calculate TICK and TRIN indicators

## Overview

In this example we will use the [Live client](https://databento.com/docs/api-live/client/live-threaded.md) to calculate two technical indicators: market tick (TICK) and the traders index (TRIN).
To do this we will request trades for all symbols and calculate these indicators for every execution.

## Trades schema

These indicators are updated on every execution for all symbols on the venue.
To get this, we will use the [trades schema](https://databento.com/docs/schemas/trades.md), which provides records for every trade execution.

## Example

```rust
use databento::{
    LiveClient, Symbols,
    dbn::{Dataset, Schema, Side, TradeMsg, TradeRec},
    live::Subscription,
};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut client = LiveClient::builder()
        .key_from_env()?
        .dataset(Dataset::GlbxMdp3)
        .build()
        .await?;
    // First, we subscribe to trades for all symbols
    client
        .subscribe(
            Subscription::builder()
                .schema(Schema::Trades)
                .symbols(Symbols::All)
                .build(),
        )
        .await?;
    client.start().await?;
    // Next, we setup our initial values for TICK and TRIN
    let mut measurements_count = 0;
    let mut uptick = 0.0;
    let mut downtick = 0.0;
    let mut upvol = 0.0;
    let mut downvol = 0.0;
    // Then, we consume 20 records calculating as we go
    while let Some(record) = client.next_record().await? {
        if let Some(trade) = record.get::<TradeMsg>() {
            if trade.side()? == Side::Ask {
                downtick += 1.0;
                downvol += trade.size as f64;
            } else if trade.side()? == Side::Bid {
                uptick += 1.0;
                upvol += trade.size as f64;
            }
            let tick = uptick / downtick;
            let trin_base = upvol / downvol;
            let trin = tick / trin_base;
            if tick.is_finite() || trin.is_finite() {
                println!("{tick:.4}, {trin:.4}");
                measurements_count += 1;
                if measurements_count == 20 {
                    break;
                }
            }
        }
    }
    // Finally, we close the connection
    client.close().await?;
    Ok(())
}
```
## Result

```plaintext
0.0000, NaN
0.0000, NaN
0.0000, NaN
0.0000, NaN
0.0000, NaN
0.0000, NaN
0.1667, 1.0000
0.3333, 0.5000
0.5000, 0.6667
0.4286, 0.6190
0.3750, 0.6250
0.3333, 0.6667
0.3000, 0.7000
0.2727, 0.7273
0.2500, 0.8611
0.3333, 0.4697
0.3077, 0.4476
0.3846, 0.5351
0.4615, 0.3992
0.5385, 0.4534
```
