OHLC.dev editorialMARKET

MarketFlow Trader Intelligence V2: Crypto Momentum & Market Analysis with Python

MarketFlow Trader Intelligence V2 is a Python-based cryptocurrency analysis workflow that combines trending assets, market breadth, momentum ranking, volume monitoring, and crypto event validation in an interactive trader dashboard.

November 28, 202625 min readRafatar
MarketFlow Trader Intelligence V2: Crypto Momentum & Market Analysis with Python

Cryptocurrency markets are highly dynamic. Asset prices can change within a short period, while trading volume, momentum, and information about crypto-related events can provide additional context for understanding market conditions. Traders therefore need a structured data-monitoring process rather than relying on a single indicator when evaluating the market.

One practical approach is to combine trending-asset data with price changes, trading volume, market capitalization, and cryptocurrency event information. These data can help traders build a watchlist, examine how many assets are rising or declining, and identify events that may require further review.

This article introduces MarketFlow Trader Intelligence V2, a Python-based cryptocurrency market analysis workflow that uses the MarketFlow All-in-One Market Finance API through RapidAPI. The system retrieves two main datasets: /trending and /crypto-events.

Trending data is used to examine assets, prices, 24-hour price changes, volume, and market capitalization when those fields are available in the API response. Crypto-event data is used to review events published or scheduled within the seven-day period preceding the UTC date on which the program is run.

The workflow goes beyond data retrieval. API responses are normalized into DataFrames, relevant columns are identified automatically, numeric values are cleaned, timestamps are converted into date formats, and event records are validated against the requested period. The analysis engine then calculates market breadth, generates momentum rankings, checks volume availability, and identifies crypto events that pass date validation.

The final output is presented through an interactive Plotly dashboard. It includes a market overview, momentum chart, five highest-performing assets (top gainers), five lowest-performing assets (top losers), volume analysis, crypto-event records, a data-quality report, and trader interpretation.

The primary purpose of this system is to provide a data-driven monitoring and decision-support tool, not to generate automatic trading signals. The code explicitly states that price momentum alone is insufficient to confirm a BUY or SELL decision. Technical confirmation, liquidity assessment, and risk management are still required before entering a trade.

2. Methodology

MarketFlow Trader Intelligence V2 is organized into five computational cells. Each cell performs a distinct function, while sharing variables and DataFrames created in the preceding stages.

Cell

Stage

Main function

Cell 1

Installation & Configuration

Installs libraries, imports modules, and configures RapidAPI authentication.

Cell 2

API Data Collection V2

Retrieves trending and crypto-event data, then saves the raw responses in JSON format.

Cell 3

Data Cleaning & Validation V2

Extracts records, normalizes JSON, identifies columns, converts numeric values, and validates event dates.

Cell 4

Trader Intelligence Engine V2

Calculates market breadth, creates momentum rankings, checks volume, evaluates crypto events, and reports decision-support status.

Cell 5

MarketFlow Trader Intelligence Dashboard V2

Displays the market overview, interactive charts, top gainers, top losers, volume, events, data quality, and trader interpretation.

2.1. System Installation and API Configuration

The first cell prepares the Python environment and installs four main libraries: Requests, Pandas, NumPy, and Plotly. Requests sends HTTP requests to the API. Pandas processes tabular data, NumPy supports numerical operations and classification, and Plotly creates interactive visualizations.

The API key is entered using the getpass() function. This allows users to enter the key without writing it directly as plain text in the notebook. The system then defines the base URL and authentication headers containing x-rapidapi-key and x-rapidapi-host.

The cell also displays a message indicating that the MarketFlow Trader Intelligence configuration is ready.

Code — Cell 1: Installation and Configuration


# CELL 1 - INSTALLATION & CONFIGURATION

!pip -q install requests pandas numpy plotly

import requests
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import json
import re
from datetime import datetime, timedelta
from getpass import getpass
from IPython.display import display, Markdown

# API CONFIGURATION
API_KEY = getpass("Masukkan RapidAPI Key: ")

BASE_URL = "https://marketflow-all-in-one-market-finance-api.p.rapidapi.com"

HEADERS = {
    "x-rapidapi-key": API_KEY,
    "x-rapidapi-host": "marketflow-all-in-one-market-finance-api.p.rapidapi.com"
}

print("MarketFlow Trader Intelligence siap digunakan.")
 

2.2. MarketFlow API Data Collection

The second cell retrieves data from two API endpoints.

Endpoint 1: /trending

This endpoint is called to obtain information about currently trending assets. In the implementation, the endpoint is called without additional parameters.

Endpoint 2: /crypto-events

This endpoint retrieves cryptocurrency event information. The program obtains the current date in UTC and calculates the starting date as seven days earlier.

The request parameters are:

Parameter

Value in the code

Purpose

skip

0

Starting point for data retrieval.

source_reliable

"true"

Requests data from sources marked as reliable by the API.

important

"false"

Sets the important filter to the submitted value.

start_date

UTC date seven days earlier

Beginning of the requested period.

end_date

Current UTC date when the program runs

End of the requested period.

The fetch_api() function sends the request using requests.get(), including the headers, parameters, and a 30-second timeout. The raise_for_status() method raises an exception when the HTTP response indicates a request failure. If the request succeeds, the response is returned in JSON format.

The raw responses from both endpoints are saved in marketflow_raw_data.json. This file contains the trending data, crypto-event data, and requested date period. Preserving the raw responses allows users to review the original source data before or after normalization.

It is important to distinguish the seven-day period used for the crypto-events request from the trending endpoint. In this implementation, /trending is called without a date filter.

Code — Cell 2: API Data Collection V2


# CELL 2 - API DATA COLLECTION V2

import requests
import json
from datetime import datetime, timedelta, timezone

today = datetime.now(timezone.utc).date()
start_date = today - timedelta(days=7)

params = {
    "skip": 0,
    "source_reliable": "true",
    "important": "false",
    "start_date": start_date.isoformat(),
    "end_date": today.isoformat()
}

def fetch_api(url, params=None):
    response = requests.get(
        url,
        headers=HEADERS,
        params=params,
        timeout=30
    )
    response.raise_for_status()
    return response.json()

print("Mengambil data MarketFlow...")

trending_data = fetch_api(
    f"{BASE_URL}/trending"
)

events_data = fetch_api(
    f"{BASE_URL}/crypto-events",
    params
)

# Simpan respons mentah
with open("marketflow_raw_data.json", "w", encoding="utf-8") as f:
    json.dump({
        "trending": trending_data,
        "crypto_events": events_data,
        "requested_period": {
            "start": str(start_date),
            "end": str(today)
        }
    }, f, indent=4, ensure_ascii=False, default=str)

print("\nAPI CONNECTION SUCCESS")
print("Trending response:", type(trending_data).__name__)
print("Events response:", type(events_data).__name__)
print("Requested period:", start_date, "to", today)

# Tampilkan informasi URL dan parameter
print("\nEvents API URL:")
print(requests.Request(
    "GET",
    f"{BASE_URL}/crypto-events",
    params=params
).prepare().url)

print("\nData mentah berhasil disimpan.")
 

2.3. Data Cleaning and Validation

The third cell transforms the JSON responses into data that can be analyzed. An API response may contain a list, a dictionary, or nested dictionaries. The system therefore uses several functions to extract records and identify columns.

A. Record extraction

The extract_records() function checks whether the data is a list whose elements are all dictionaries. If so, it returns the list as a collection of records. Otherwise, it recursively examines list elements or dictionary values.

For dictionaries, the function first checks commonly used keys: data, results, trending, events, items, and coins. If records are not found there, it examines the remaining dictionary values.

B. Converting JSON into DataFrames

The to_dataframe() function calls extract_records() and converts the extracted records into a Pandas DataFrame using pd.json_normalize(). The sep="_" parameter separates nested field names with an underscore.

The resulting datasets are stored in df_trending and df_events_raw. A copy of the event data is then created as df_events for validation, while preserving the original dataset separately.

C. Automatic column detection

The find_column() function searches for column names using regular expressions. The search is case-insensitive. The system looks for the following field groups:

Information

Search patterns

Asset name

^name$, ^symbol$

Symbol

^symbol$

Price

^price_usd$, current_price

Price change

^price_change_24h$, price_change, change_percent

Volume

^volume$, total_volume

Market capitalization

^market_cap$, marketcap

Event start date

^date_start$

Event publication date

^date_public$

These patterns are the search rules implemented in the code. They do not guarantee that every API response will contain fields with exactly these names. If a field is not found, its corresponding column variable is set to None.

D. Numeric conversion

The convert_numeric() function removes currency symbols, commas, spaces, and percentage signs before converting values into numeric data. Conversion is performed using pd.to_numeric(). Values that cannot be converted become NaN.

This process is applied to the price, price-change, volume, and market-capitalization columns when those columns are successfully identified.

E. Timestamp conversion

The parse_timestamp() function handles both numeric timestamps and date values represented as text. For numeric timestamps, the system estimates whether the unit is milliseconds or seconds based on the median absolute value. If the median is greater than \(10^{12}\), the unit is treated as milliseconds; otherwise, it is treated as seconds.

The converted timestamps use UTC. Values that cannot be converted become NaT.

F. Event date validation

The system prioritizes date_start as the event date. If that date is unavailable or cannot be converted, it uses date_public as a fallback. If neither is available, event_date is set to NaT.

Period validation uses the starting date from seven days earlier and an end boundary corresponding to the beginning of the following day in UTC. Therefore, retained records must satisfy:

\[ Start_{UTC} \leq EventDate < End_{UTC} \]

Events outside this period are excluded from df_events, while a copy of all processed events remains available in df_events_all. After date validation, duplicates are removed based on whichever of the following columns are available: ticker, symbol, caption, and event_date.

G. Data-quality report

The final stage displays the number of trending records, raw events, events within the requested period, and events outside the period. It also reports the availability of price, price-change, and volume columns. This report helps users understand data completeness before interpreting the analysis.

Code — Cell 3: Data Cleaning and Validation V2


# CELL 3 - DATA CLEANING & VALIDATION V2

import pandas as pd
import numpy as np
import re

def extract_records(data):
    if isinstance(data, list):
        if all(isinstance(x, dict) for x in data):
            return data

        for item in data:
            result = extract_records(item)
            if result is not None:
                return result

    elif isinstance(data, dict):
        for key in [
            "data", "results", "trending",
            "events", "items", "coins"
        ]:
            if key in data:
                result = extract_records(data[key])
                if result is not None:
                    return result

        for value in data.values():
            result = extract_records(value)
            if result is not None:
                return result

    return None


def to_dataframe(data):
    records = extract_records(data)
    return pd.json_normalize(records, sep="_") if records else pd.DataFrame()


def find_column(df, patterns):
    for pattern in patterns:
        for col in df.columns:
            if re.search(pattern, col, re.I):
                return col
    return None


def convert_numeric(series):
    return pd.to_numeric(
        series.astype(str).str.replace(r"[$,% ,]", "", regex=True),
        errors="coerce"
    )


# EXTRACT DATA
df_trending = to_dataframe(trending_data)
df_events_raw = to_dataframe(events_data)

df_events = df_events_raw.copy()

# TRENDING COLUMN DETECTION
name_col = find_column(df_trending, [r"^name$", r"^symbol$"])
symbol_col = find_column(df_trending, [r"^symbol$"])
price_col = find_column(df_trending, [r"^price_usd$", r"current_price"])
change_col = find_column(
    df_trending,
    [r"^price_change_24h$", r"price_change", r"change_percent"]
)
volume_col = find_column(df_trending, [r"^volume$", r"total_volume"])
market_cap_col = find_column(
    df_trending, [r"^market_cap$", r"marketcap"]
)

# CONVERT TRENDING DATA
for col in [price_col, change_col, volume_col, market_cap_col]:
    if col:
        df_trending[col] = convert_numeric(df_trending[col])

# EVENT TIMESTAMP CONVERSION
def parse_timestamp(series):
    numeric = pd.to_numeric(series, errors="coerce")

    result = pd.Series(
        pd.NaT, index=series.index, dtype="datetime64[ns, UTC]"
    )

    numeric_mask = numeric.notna()

    if numeric_mask.any():
        sample = numeric[numeric_mask]
        unit = "ms" if sample.abs().median() > 1e12 else "s"

        result.loc[numeric_mask] = pd.to_datetime(
            numeric[numeric_mask],
            unit=unit,
            errors="coerce",
            utc=True
        )

    text_mask = ~numeric_mask
    if text_mask.any():
        result.loc[text_mask] = pd.to_datetime(
            series[text_mask],
            errors="coerce",
            utc=True
        )

    return result


date_start_col = find_column(df_events, [r"^date_start$"])
date_public_col = find_column(df_events, [r"^date_public$"])

if date_start_col:
    df_events["date_start_dt"] = parse_timestamp(
        df_events[date_start_col]
    )

if date_public_col:
    df_events["date_public_dt"] = parse_timestamp(
        df_events[date_public_col]
    )

# USE EVENT START DATE, FALLBACK TO PUBLICATION DATE
if "date_start_dt" in df_events.columns:
    df_events["event_date"] = df_events["date_start_dt"]

    if "date_public_dt" in df_events.columns:
        df_events["event_date"] = (
            df_events["event_date"].fillna(
                df_events["date_public_dt"]
            )
        )

elif "date_public_dt" in df_events.columns:
    df_events["event_date"] = df_events["date_public_dt"]

else:
    df_events["event_date"] = pd.NaT

# CLIENT-SIDE DATE VALIDATION
start_utc = pd.Timestamp(start_date, tz="UTC")
end_utc = pd.Timestamp(today + timedelta(days=1), tz="UTC")

valid_mask = (
    df_events["event_date"].ge(start_utc) &
    df_events["event_date"].lt(end_utc)
)

df_events["date_valid"] = valid_mask

# Keep original data separately
df_events_all = df_events.copy()

# Only valid date events
df_events = df_events[valid_mask].copy()

# REMOVE DUPLICATES
if len(df_events) > 0:
    duplicate_cols = [
        c for c in ["ticker", "symbol", "caption", "event_date"]
        if c in df_events.columns
    ]

    if duplicate_cols:
        df_events = df_events.drop_duplicates(
            subset=duplicate_cols
        )

# DATA QUALITY REPORT
volume_valid = (
    df_trending[volume_col].notna().sum()
    if volume_col else 0
)

print("=" * 55)
print("DATA QUALITY REPORT")
print("=" * 55)

print("Trending records:", len(df_trending))
print("Raw events:", len(df_events_raw))
print("Events in requested period:", len(df_events))
print("Events outside requested period:",
      len(df_events_all) - len(df_events))

print("\nTRENDING VALIDATION")
print("Price column:", price_col)
print("Change column:", change_col)
print("Volume column:", volume_col)
print("Valid volume records:", volume_valid)

if volume_col:
    print("Volume completeness:",
          round(volume_valid / max(len(df_trending), 1) * 100, 2), "%")

print("\nEVENT VALIDATION")
print("Date column:", date_start_col or date_public_col)

if len(df_events_all) > 0:
    print("Oldest event:",
          df_events_all["event_date"].min())
    print("Newest event:",
          df_events_all["event_date"].max())

print("\nDATA VALIDATION COMPLETED")
 

2.4. Trader Intelligence Engine

The fourth cell processes the data prepared in Cell 3. The analysis engine consists of five components.

A. Market breadth analysis

Market breadth examines the distribution of price changes among assets with valid change values. The data is divided into three groups:

  • Positive assets: price changes greater than zero.

  • Negative assets: price changes below zero.

  • Neutral assets: price changes equal to zero.

Positive breadth is calculated using:

\[ Positive\ Breadth = \frac{Positive\ Assets}{Valid\ Price\ Changes}\times 100\% \]

In this implementation, the denominator is the number of non-missing price-change observations (NaN values are excluded), not the total number of trending records.

The system classifies market conditions using the following thresholds:

Positive breadth

System classification

60% or higher

POSITIVE BREADTH

40% or lower

NEGATIVE BREADTH

Above 40% and below 60%

MIXED MARKET

These thresholds are descriptive classification rules defined in the code. They do not, by themselves, establish the future direction of the market.

The system also calculates the average 24-hour change across all valid price-change values.

B. Momentum ranking

Momentum ranking sorts assets from the highest to the lowest price change. Records without a price-change value are excluded from the ranking process.

After sorting, the system creates a Momentum Rank column beginning at rank 1. The Momentum Status column is determined by the price-change value:

  • POSITIVE for a change above zero.

  • NEGATIVE for a change below zero.

  • NEUTRAL for a change equal to zero.

The output is limited to the top 15 records and includes only columns available in the DataFrame.

C. Volume analysis

The volume component checks whether a volume column has been identified and contains valid values. If available, the system calculates the number of valid records, average volume, and median volume.

If the column is unavailable or all its values are missing, the system reports that volume confirmation cannot be performed. Volume is therefore not treated as an indicator that is always available.

D. Crypto event risk

This component checks events that passed the date validation performed in Cell 3. If data is available, the system searches for the impact and important columns.

When the impact column is found, its values are converted to lowercase and the distribution is displayed. When the important column is found, the system counts events whose text values are true or 1.

If no valid events are available, the system displays a warning not to use historical events as current catalysts.

E. Trader decision support and data confidence

This section summarizes the number of valid price records, valid price-change records, volume status, event status, and market-breadth condition.

If price-change data is available, the system creates a watchlist based on 24-hour momentum. However, the code does not convert momentum into BUY or SELL signals. Its output explicitly states that a trading decision has not been confirmed because technical and liquidity confirmation are not yet available.

Code — Cell 4: Trader Intelligence Engine V2


# CELL 4 - TRADER INTELLIGENCE ENGINE V2

# 1. MARKET BREADTH
print("=" * 60)
print("MARKET BREADTH ANALYSIS")
print("=" * 60)

if change_col and df_trending[change_col].notna().any():

    valid_changes = df_trending[change_col].dropna()

    positive = int((valid_changes > 0).sum())
    negative = int((valid_changes < 0).sum())
    neutral = int((valid_changes == 0).sum())

    breadth = positive / len(valid_changes) * 100

    print("Positive assets:", positive)
    print("Negative assets:", negative)
    print("Neutral assets:", neutral)
    print("Positive breadth:", round(breadth, 2), "%")
    print("Average 24H change:",
          round(valid_changes.mean(), 2), "%")

    if breadth >= 60:
        market_condition = "POSITIVE BREADTH"
    elif breadth <= 40:
        market_condition = "NEGATIVE BREADTH"
    else:
        market_condition = "MIXED MARKET"

else:
    positive = negative = neutral = 0
    breadth = np.nan
    market_condition = "INSUFFICIENT DATA"

print("Market Condition:", market_condition)


# 2. MOMENTUM RANKING
print("\n" + "=" * 60)
print("MOMENTUM RANKING")
print("=" * 60)

watchlist = df_trending.copy()

if change_col:
    watchlist = watchlist.dropna(subset=[change_col])

    watchlist = watchlist.sort_values(
        change_col, ascending=False
    ).reset_index(drop=True)

    watchlist["Momentum Rank"] = range(
        1, len(watchlist) + 1
    )

    watchlist["Momentum Status"] = np.select(
        [
            watchlist[change_col] > 0,
            watchlist[change_col] < 0
        ],
        [
            "POSITIVE",
            "NEGATIVE"
        ],
        default="NEUTRAL"
    )

    display_cols = [
        c for c in [
            "Momentum Rank", name_col, symbol_col,
            price_col, change_col, volume_col,
            market_cap_col, "Momentum Status"
        ]
        if c and c in watchlist.columns
    ]

    display(watchlist[display_cols].head(15))

else:
    watchlist["Momentum Status"] = "INSUFFICIENT DATA"
    print("Perubahan harga tidak tersedia.")


# 3. VOLUME VALIDATION
print("\n" + "=" * 60)
print("VOLUME ANALYSIS")
print("=" * 60)

if volume_col and watchlist[volume_col].notna().any():
    volume_valid = watchlist[volume_col].dropna()

    print("Valid volume records:", len(volume_valid))
    print("Average volume:", volume_valid.mean())
    print("Volume median:", volume_valid.median())

    volume_status = "AVAILABLE"

else:
    print("Volume tidak tersedia atau seluruhnya NaN.")
    print("Volume confirmation: NOT POSSIBLE")

    volume_status = "UNAVAILABLE"


# 4. CRYPTO EVENT RISK
print("\n" + "=" * 60)
print("CRYPTO EVENT RISK")
print("=" * 60)

if len(df_events) > 0:

    impact_col = find_column(df_events, [r"^impact$"])
    important_col = find_column(df_events, [r"^important$"])

    if impact_col:
        df_events["Impact Level"] = (
            df_events[impact_col]
            .astype(str)
            .str.lower()
        )

        print("Event impact distribution:")
        display(df_events["Impact Level"].value_counts())

    if important_col:
        print("Important events:",
              df_events[important_col].astype(str)
              .str.lower().isin(["true", "1"]).sum())

    event_status = "EVENTS FOUND - REVIEW REQUIRED"

else:
    print("Tidak ada event dengan tanggal valid.")
    print("Jangan menggunakan event historis sebagai katalis terkini.")

    event_status = "NO VALID EVENTS"


# 5. DATA CONFIDENCE
print("\n" + "=" * 60)
print("TRADER DECISION SUPPORT")
print("=" * 60)

valid_price = (
    df_trending[price_col].notna().sum()
    if price_col else 0
)

valid_change = (
    df_trending[change_col].notna().sum()
    if change_col else 0
)

print("Valid price records:", valid_price)
print("Valid change records:", valid_change)
print("Volume status:", volume_status)
print("Event status:", event_status)
print("Market condition:", market_condition)

if valid_change > 0:
    print("\nWATCHLIST: Berdasarkan momentum 24 jam.")
    print("BUY/SELL: Belum dikonfirmasi.")
    print("Reason: Belum tersedia konfirmasi teknikal dan likuiditas.")
else:
    print("\nDECISION: INSUFFICIENT DATA")

print("\nRisk management tetap diperlukan sebelum entry.")
 

2.5. Professional Trader Dashboard

The fifth cell presents the analysis in a single dashboard using Plotly and IPython display components. At the beginning, market metrics are recalculated so that the summary values reflect the DataFrames currently being used.

The dashboard contains eight information sections and one trader-interpretation section.

1. Market Overview

This section displays the number of trending assets, positive, negative, and neutral assets, positive breadth, average 24-hour change, valid crypto events, valid volume records, and market-condition classification.

2. Market Momentum

The interactive bar chart displays up to 15 assets with the highest price changes. Bar colors are grouped by momentum status. A horizontal line at zero separates positive and negative changes.

3. Top 5 Gainers

The table displays up to five assets with the highest price changes. The displayed columns depend on the availability of asset name, symbol, price, and price-change fields.

4. Top 5 Losers

The table displays up to five assets with the lowest price changes based on the available numeric values.

5. Volume Analysis

This section displays up to ten records with the highest volume, sorted in descending order. If volume is unavailable, the dashboard states that volume confirmation cannot be performed.

6. Valid Crypto Events

The displayed event list is taken only from df_events, meaning the records have passed date validation and duplicate removal. The displayed fields include ticker, symbol, caption, event date, impact, important, source, and source reliability when available.

7. Data Quality Report

The report compares the available record counts for trending assets, price, price change, volume, raw events, and date-validated events. Each data group is assigned a status such as AVAILABLE, MISSING, UNAVAILABLE, RECEIVED, or NO VALID DATA, according to the conditions defined in the code.

8. Trader Interpretation

The interpretation section presents the market-breadth condition and a summary of key metrics. It also issues warnings when valid volume or event data is unavailable.

At the end, the system displays the decision-support message:

TRADING DECISION: WAIT FOR FURTHER CONFIRMATION

This message is important because the dashboard is designed as an analytical support tool, not an automatic entry-signal generator. The code provides three main reasons: there is no confirmed technical entry signal, price momentum alone is insufficient, and risk management must be established before entering a trade.

Cell 5 does not export Excel files or provide downloadable data files. This version displays its results directly in the notebook through tables, text, and interactive Plotly charts.

Code — Cell 5: MarketFlow Trader Intelligence Dashboard V2


# ============================================================
# CELL 5 - MARKETFLOW TRADER INTELLIGENCE DASHBOARD V2
# NO EXCEL EXPORT | NO FILE DOWNLOAD
# ============================================================

from IPython.display import display, Markdown
import pandas as pd
import numpy as np
import plotly.express as px

# ============================================================
# 1. RECALCULATE MARKET METRICS
# ============================================================

total_assets = len(df_trending)

valid_price_count = (
    int(df_trending[price_col].notna().sum())
    if price_col and price_col in df_trending.columns
    else 0
)

valid_change_count = (
    int(df_trending[change_col].notna().sum())
    if change_col and change_col in df_trending.columns
    else 0
)

valid_volume_count = (
    int(df_trending[volume_col].notna().sum())
    if volume_col and volume_col in df_trending.columns
    else 0
)

raw_event_count = len(df_events_raw)
valid_event_count = len(df_events)

# Market breadth
if valid_change_count > 0:

    valid_changes = df_trending[change_col].dropna()

    positive = int((valid_changes > 0).sum())
    negative = int((valid_changes < 0).sum())
    neutral = int((valid_changes == 0).sum())

    breadth = positive / valid_change_count * 100
    avg_change = valid_changes.mean()

    if breadth >= 60:
        market_condition = "POSITIVE BREADTH"
    elif breadth <= 40:
        market_condition = "NEGATIVE BREADTH"
    else:
        market_condition = "MIXED MARKET"

else:
    positive = negative = neutral = 0
    breadth = np.nan
    avg_change = np.nan
    market_condition = "INSUFFICIENT DATA"


# ============================================================
# 2. DASHBOARD HEADER
# ============================================================

display(Markdown("""
# 📊 MARKETFLOW TRADER INTELLIGENCE V2
### Market Overview & Crypto Momentum Analysis
"""))

display(Markdown(
    f"**Analysis Date:** {today} UTC  \n"
    f"**Event Period:** {start_date} to {today}"
))


# ============================================================
# 3. MARKET OVERVIEW
# ============================================================

display(Markdown("## 1. Market Overview"))

overview = pd.DataFrame({
    "Metric": [
        "Trending Assets",
        "Positive Assets",
        "Negative Assets",
        "Neutral Assets",
        "Positive Breadth",
        "Average 24H Change",
        "Valid Crypto Events",
        "Valid Volume Records",
        "Market Condition"
    ],

    "Result": [
        total_assets,
        positive,
        negative,
        neutral,
        f"{breadth:.2f}%" if pd.notna(breadth) else "N/A",
        f"{avg_change:.2f}%" if pd.notna(avg_change) else "N/A",
        valid_event_count,
        valid_volume_count,
        market_condition
    ]
})

display(overview)


# ============================================================
# 4. MOMENTUM ANALYSIS
# ============================================================

display(Markdown("## 2. Market Momentum"))

if change_col and name_col and valid_change_count > 0:

    chart_df = df_trending.dropna(
        subset=[change_col]
    ).copy()

    chart_df = chart_df.sort_values(
        change_col,
        ascending=False
    ).head(15)

    chart_df["Momentum Status"] = np.select(
        [
            chart_df[change_col] > 0,
            chart_df[change_col] < 0
        ],
        [
            "POSITIVE",
            "NEGATIVE"
        ],
        default="NEUTRAL"
    )

    fig = px.bar(
        chart_df,
        x=name_col,
        y=change_col,
        color="Momentum Status",
        title="Trending Assets - 24H Price Change (%)",
        hover_data=[
            c for c in [symbol_col, price_col]
            if c and c in chart_df.columns
        ]
    )

    fig.add_hline(
        y=0,
        line_dash="dash",
        annotation_text="Zero Change"
    )

    fig.update_layout(
        xaxis_tickangle=-35,
        height=550
    )

    fig.show()

else:
    print("Momentum data unavailable.")


# ============================================================
# 5. TOP GAINERS
# ============================================================

display(Markdown("## 3. Top 5 Gainers"))

if change_col and valid_change_count > 0:

    gainers = df_trending.dropna(
        subset=[change_col]
    ).nlargest(5, change_col)

    display(
        gainers[
            [
                c for c in [
                    name_col,
                    symbol_col,
                    price_col,
                    change_col
                ]
                if c and c in gainers.columns
            ]
        ].reset_index(drop=True)
    )

else:
    print("Gainer data unavailable.")


# ============================================================
# 6. TOP LOSERS
# ============================================================

display(Markdown("## 4. Top 5 Losers"))

if change_col and valid_change_count > 0:

    losers = df_trending.dropna(
        subset=[change_col]
    ).nsmallest(5, change_col)

    display(
        losers[
            [
                c for c in [
                    name_col,
                    symbol_col,
                    price_col,
                    change_col
                ]
                if c and c in losers.columns
            ]
        ].reset_index(drop=True)
    )

else:
    print("Loser data unavailable.")


# ============================================================
# 7. VOLUME ANALYSIS
# ============================================================

display(Markdown("## 5. Volume Analysis"))

if volume_col and valid_volume_count > 0:

    volume_data = df_trending.dropna(
        subset=[volume_col]
    ).copy()

    display(
        volume_data[
            [
                c for c in [
                    name_col,
                    symbol_col,
                    price_col,
                    change_col,
                    volume_col
                ]
                if c and c in volume_data.columns
            ]
        ].sort_values(
            volume_col,
            ascending=False
        ).head(10)
    )

    print("Valid volume records:", valid_volume_count)

else:
    print("Volume unavailable or all values are missing.")
    print("Volume confirmation cannot be performed.")


# ============================================================
# 8. CRYPTO EVENTS
# ============================================================

display(Markdown("## 6. Valid Crypto Events"))

if valid_event_count > 0:

    event_cols = [
        c for c in [
            "ticker",
            "symbol",
            "caption",
            "event_date",
            "impact",
            "important",
            "source",
            "source_reliable"
        ]
        if c in df_events.columns
    ]

    display(
        df_events[event_cols].sort_values(
            "event_date"
        )
    )

else:
    print("No valid events in the requested period.")
    print("Historical events have been excluded.")


# ============================================================
# 9. DATA QUALITY REPORT
# ============================================================

display(Markdown("## 7. Data Quality Report"))

quality = pd.DataFrame({
    "Data": [
        "Trending Assets",
        "Price",
        "Price Change",
        "Volume",
        "Raw Events",
        "Date-Validated Events"
    ],

    "Valid Records": [
        total_assets,
        valid_price_count,
        valid_change_count,
        valid_volume_count,
        raw_event_count,
        valid_event_count
    ],

    "Status": [
        "AVAILABLE" if total_assets > 0 else "MISSING",
        "AVAILABLE" if valid_price_count > 0 else "MISSING",
        "AVAILABLE" if valid_change_count > 0 else "MISSING",
        "AVAILABLE" if valid_volume_count > 0 else "UNAVAILABLE",
        "RECEIVED" if raw_event_count > 0 else "MISSING",
        "AVAILABLE" if valid_event_count > 0 else "NO VALID DATA"
    ]
})

display(quality)


# ============================================================
# 10. TRADER INTERPRETATION
# ============================================================

display(Markdown("## 8. Trader Interpretation"))

print("=" * 55)
print("MARKET ANALYSIS")
print("=" * 55)

print("Market Condition :", market_condition)

if pd.notna(breadth):
    print(f"Positive Breadth  : {breadth:.2f}%")

if pd.notna(avg_change):
    print(f"Average 24H Change: {avg_change:.2f}%")

print("Trending Assets   :", total_assets)
print("Positive Assets   :", positive)
print("Negative Assets   :", negative)
print("Valid Volume      :", valid_volume_count)
print("Valid Events      :", valid_event_count)


# AUTOMATIC INTERPRETATION

print("\n" + "=" * 55)
print("TRADER DECISION SUPPORT")
print("=" * 55)

if market_condition == "NEGATIVE BREADTH":
    print("Market Observation: NEGATIVE BREADTH")
    print("Interpretation: More assets are declining than rising.")

elif market_condition == "POSITIVE BREADTH":
    print("Market Observation: POSITIVE BREADTH")
    print("Interpretation: More assets are rising than declining.")

elif market_condition == "MIXED MARKET":
    print("Market Observation: MIXED MARKET")
    print("Interpretation: Market direction is not broadly aligned.")

else:
    print("Market Observation: INSUFFICIENT DATA")

if valid_volume_count == 0:
    print("\nWARNING: Volume confirmation unavailable.")

if valid_event_count == 0:
    print("WARNING: No date-validated crypto events.")

if valid_change_count > 0:
    print("\nMomentum Ranking: AVAILABLE")
else:
    print("\nMomentum Ranking: INSUFFICIENT DATA")

print("\nTRADING DECISION: WAIT FOR FURTHER CONFIRMATION")

print("Reason:")
print("- No confirmed technical entry signal.")
print("- Price momentum alone is insufficient.")
print("- Risk management must be established before entry.")

print("\n" + "=" * 55)
print("MARKETFLOW TRADER INTELLIGENCE V2")
print("DASHBOARD COMPLETED SUCCESSFULLY")
print("=" * 55)
 

Result:

result


3. Results and Discussion

3.1. Integrated Market Data Collection

The workflow combines two information sources from the MarketFlow API. The /trending endpoint provides information about currently trending assets, while /crypto-events provides cryptocurrency event data based on the submitted period and filter parameters.

Both responses are first stored in marketflow_raw_data.json. Separating raw data from processed data is important because it allows users to review the original API response if inconsistencies occur during extraction or normalization.

The actual number of records and fields received depends on the API response at the time the notebook is executed. Because the supplied file contains program code rather than executed API output, this article does not claim specific asset counts, coin names, prices, or events as actual results.

3.2. Data Quality and Date Validation

Data validation is an important component of the system. Not every record received from the API is automatically used in event analysis. The system checks event dates and retains records that fall within the requested period.

The separation of df_events_raw, df_events_all, and df_events distinguishes the raw data, processed event data with date-processing results, and event data that passes period filtering and deduplication.

For trending data, the quality report checks the availability of price, price-change, and volume columns. This information matters because an analysis can only be calculated when the required fields are available and successfully converted into numeric values.

3.3. Market Breadth as a Market Condition Indicator

Market breadth provides an overview of the proportion of assets experiencing gains relative to all assets with valid price-change values. This indicator helps avoid relying on the performance of only one asset when assessing the market.

A high positive-breadth value indicates that more asset observations are rising than falling. Conversely, a low positive-breadth value indicates that declining observations are more dominant. However, the result describes only the distribution of price changes in the dataset returned by the API, not the entire cryptocurrency market.

The POSITIVE BREADTH, NEGATIVE BREADTH, and MIXED MARKET classifications use the 60% and 40% thresholds defined in the program. These thresholds are descriptive program rules, not universal standards or guarantees of future price direction.

3.4. Momentum Ranking and Watchlist Development

Momentum ranking sorts assets according to the available price-change values. This allows users to identify assets with the highest and lowest relative changes within the trending dataset.

The resulting watchlist can serve as a starting point for further investigation. An asset with positive momentum is not necessarily suitable for buying, and an asset with negative momentum does not necessarily need to be sold. Such decisions require additional examination of price structure, liquidity, volatility, technical levels, and the trader's risk profile.

3.5. Volume as a Confirmation Component

Volume provides supporting information for assessing trading activity. The system calculates the number of valid volume records, the average, and the median. The dashboard also displays up to ten assets with the highest volume.

However, the availability of volume does not automatically prove market liquidity quality or signal validity. Volume interpretation should consider the API field definition, unit, measurement period, and consistency of the data source.

If volume is unavailable, the system explicitly reports that volume confirmation cannot be performed. This is more informative than treating missing data as zero volume.

3.6. Crypto Events and Event Risk Monitoring

Crypto-event information provides additional context about market activity. Events can be reviewed by date, impact, important status, ticker, symbol, source, and source reliability when those fields are available.

Date validation is necessary to prevent events outside the analysis period from being mixed with events currently being monitored. The system also displays a warning when no valid events are available. This helps prevent historical events from being treated as current market catalysts.

3.7. Interactive Dashboard and Trader Decision Support

The dashboard combines the market overview, momentum chart, gainers and losers lists, volume, crypto events, and data-quality report. This presentation allows users to review several aspects of the market from one interface.

The Trader Interpretation component connects calculated results with readable messages. Nevertheless, the system deliberately limits its interpretation. The final message, WAIT FOR FURTHER CONFIRMATION, emphasizes that trending data and momentum alone are not sufficient to produce a confirmed trading decision.

3.8. System Limitations and Considerations

Several limitations should be considered when using MarketFlow Trader Intelligence V2.

  1. Dependence on the API response structure. The system searches for columns using predefined name patterns. If the API uses different field names, some information may not be detected.

  2. Availability of numeric data. Momentum, breadth, and volume calculations depend on fields being identified and successfully converted.

  3. Event periods use UTC. Date boundaries are calculated using UTC dates, which may differ from the user's local date.

  4. Event validation depends on timestamps. The system prioritizes the event start date and uses the publication date as a fallback. Date interpretation still depends on the quality of the source data.

  5. Event filtering follows the API parameters. The code sends source_reliable=true and important=false. The returned results depend on how the API handles those parameters.

  6. Market breadth represents only the retrieved dataset. It does not automatically represent every asset or the entire cryptocurrency market.

  7. Volume is not a standalone trading confirmation. The availability of volume does not automatically establish sufficient liquidity or signal validity.

  8. No advanced technical indicators are implemented. The code does not calculate RSI, MACD, moving averages, support and resistance, or price predictions.

  9. There are no automatic BUY/SELL signals. The system explicitly requires further confirmation and risk management.

  10. The dashboard does not export Excel files. This version displays results directly in the notebook and explicitly specifies no Excel export and no file download.

Future development could include technical indicators, historical data comparisons, volatility analysis, more measurable liquidity monitoring, and the recording of analysis results over time. Each addition should be accompanied by clear data definitions and calculation methods.

4. Conclusion

MarketFlow Trader Intelligence V2 is a Python-based cryptocurrency analysis workflow that integrates trending data and crypto events from the MarketFlow All-in-One Market Finance API.

The system runs through five main stages: library and API configuration, data retrieval, cleaning and validation, trader intelligence analysis, and interactive dashboard presentation.

For market analysis, the system calculates positive breadth, classifies market conditions, generates momentum rankings, and checks volume availability. For event monitoring, it retrieves crypto events, converts timestamps, validates the date period, and displays events that meet the processing criteria.

The dashboard brings the analysis together through metric summaries, a momentum chart, top gainers, top losers, volume analysis, valid crypto events, a data-quality report, and trader interpretation.

Although the system provides useful information for building a watchlist and monitoring market conditions, it remains a descriptive analytical tool. Price momentum, market breadth, volume, and events should not be used independently as the basis for a trading decision. Technical confirmation, liquidity assessment, and risk management are still required before entering a trade.

With its five-cell structure, MarketFlow Trader Intelligence V2 provides a foundation for a workflow that can be further developed into a more comprehensive cryptocurrency market-monitoring system.