Cryptocurrency markets operate continuously and can experience rapid price movements. Traders therefore use technical indicators to organize market information and assess prevailing market conditions. The Simple Moving Average (SMA) summarizes a series of price observations, while the Volume Weighted Average Price (VWAP) incorporates both price and traded volume.
Examining SMA and VWAP together provides two complementary reference points. The latest SMA can be positioned above, below, or at the VWAP value. Its movement relative to the preceding SMA observation can also be classified as rising, falling, or flat. Combining these observations creates a transparent, rule-based market classification.
This article presents BTC Trading Analysis using SMA and VWAP through a Python workflow connected to the MarketFlow All-in-One Market Finance API through RapidAPI. This BTC Trading Analysis workflow retrieves SMA indicator data for BTC and VWAP data for BTCUSDT. The system retrieves SMA indicator data for BTC and VWAP data for BTCUSDT, processes the returned values, calculates SMA momentum, compares the latest SMA value with VWAP, and generates a rule-based trading observation. This practical BTC trading analysis workflow demonstrates how Python can organize indicator data into clear market conditions without presenting the resulting classification as a guaranteed prediction.
The implementation is organized into five computational cells. Each cell is presented with its complete original Python code, followed by an explanation of its purpose and operation. The article concludes with the system's overall findings and SEO metadata.
The BULLISH, BEARISH, and NEUTRAL labels are outputs of the conditions explicitly implemented in the code. They are descriptive decision-support labels, not guarantees of future price direction or standalone instructions to enter or exit a trade.
2. BTC Trading Analysis: Code Implementation and Explanation
Cell 1: Library Imports and Basic Configuration
Purpose
The first cell establishes the Python environment and configures access to the MarketFlow API. It imports the libraries required for HTTP requests, data processing, numerical operations, JSON inspection, visualization, secure API-key input, and notebook output.
The script defines the API base URL and places the RapidAPI key in the request headers. It also sets BTCUSDT as the trading symbol, BTC as the indicator symbol, and 14 as the period variable. The API key is requested with getpass, so it is not displayed as ordinary input while being entered.
Complete code:
# -*- coding: utf-8 -*-
"""marketflow 3.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1xIRX8hLaAmmmMpYPzQKU2hV92-9XBubl
CELL 1. Import library dan konfigurasi dasar
"""
import requests
import pandas as pd
import numpy as np
import json
import matplotlib.pyplot as plt
from getpass import getpass
from IPython.display import display
BASE_URL = "https://marketflow-all-in-one-market-finance-api.p.rapidapi.com"
API_KEY = getpass("Masukkan RapidAPI Key: ")
HEADERS = {
"x-rapidapi-key": API_KEY,
"x-rapidapi-host": "marketflow-all-in-one-market-finance-api.p.rapidapi.com"
}
SYMBOL = "BTCUSDT"
INDICATOR_SYMBOL = "BTC"
PERIOD = 14Cell 2: Retrieving SMA Indicator Data
Purpose
The second cell prepares and sends a request to the /tools/indicator endpoint. The request specifies the indicator type as SMA and uses BTC as the indicator symbol.
The parameter dictionary also supplies kPeriod, spanBPeriod, displacement, signalPeriod, stdDev, dPeriod, basePeriod, fastPeriod, period, slowPeriod, and conversionPeriod. These values are passed to the API as written in the source code.
The request uses the configured authentication headers and a 30-second timeout. raise_for_status() raises an exception if the HTTP response indicates a request failure. When successful, the response is converted from JSON and stored in indicator_data. The complete response is printed so its structure can be inspected.
The subsequent processing cell expects the SMA values to be accessible through data.values, either directly in the response or in the first element when the response is a list.
Complete code:
"""CELL 2. Mengambil data indikator SMA"""
params = {
"kPeriod": 14,
"spanBPeriod": 52,
"displacement": 26,
"signalPeriod": 9,
"stdDev": 2,
"dPeriod": 3,
"basePeriod": 26,
"fastPeriod": 12,
"period": 14,
"slowPeriod": 26,
"conversionPeriod": 9,
"type": "crypto",
"indicator": "SMA",
"symbol": INDICATOR_SYMBOL
}
response_indicator = requests.get(
f"{BASE_URL}/tools/indicator",
headers=HEADERS,
params=params,
timeout=30
)
response_indicator.raise_for_status()
indicator_data = response_indicator.json()
print(json.dumps(indicator_data, indent=2))Cell 3: Retrieving VWAP Data
Purpose
The third cell requests VWAP information from the /tools/crypto/vwap endpoint using BTCUSDT as the requested symbol.
The script prints the HTTP status code and attempts to parse the response as JSON. If JSON parsing fails, it prints the response text instead. When the status code is 200, the response is assigned to vwap_data and a success message is displayed. Otherwise, the script prints a failure message and the API-provided message when available.
The next processing stage expects the VWAP response to contain the vwap and total_volume fields.
Complete code:
"""CELL 3. Mengambil data VWAP"""
# CELL 3 — VWAP API FIX
url = f"{BASE_URL}/tools/crypto/vwap"
params_vwap = {
"symbol": "BTCUSDT"
}
response_vwap = requests.get(
url,
headers=HEADERS,
params=params_vwap,
timeout=30
)
print("HTTP STATUS:", response_vwap.status_code)
try:
result = response_vwap.json()
print(json.dumps(result, indent=2))
except:
print(response_vwap.text)
if response_vwap.status_code == 200:
vwap_data = result
print("\nSUCCESS: VWAP DATA BERHASIL DIAMBIL!")
else:
print("\nVWAP REQUEST FAILED")
print("Server message:", result.get("message", "Unknown error")
if isinstance(result, dict) else result)Cell 4: Data Processing and Visualization
Purpose
The fourth cell performs the core data preparation for BTC Trading Analysis. It extracts the VWAP value and total volume from the API response and retrieves the SMA values from the indicator response. The SMA observations are converted into numeric values and organized in a Pandas DataFrame. Invalid observations are removed before calculations are performed.
The script calculates the change between consecutive SMA observations:
\[ \Delta SMA_t = SMA_t - SMA_{t-1} \]
It then assigns a trend label based on the sign of the change:
Condition | Trend classification |
|---|---|
| UP |
| DOWN |
| FLAT |
The latest and previous SMA values are selected. The percentage distance between the latest SMA and VWAP is calculated as:
\[ Distance(\%) = \frac{Latest\ SMA - VWAP}{VWAP} \times 100 \]
A positive result means the latest SMA is above VWAP, while a negative result means it is below VWAP. A zero result indicates that the two values are equal.
The cell prints the BTC market data, displays the ten latest SMA observations, and creates a chart containing the SMA series and a horizontal VWAP reference line.
Complete code:
"""CELL 4. Pengolahan dan visualisasi data"""
# CELL 4 — DATA PROCESSING
# Ambil data VWAP
vwap_value = float(vwap_data["vwap"])
total_volume = float(vwap_data["total_volume"])
# Ambil data indikator SMA
indicator_info = indicator_data[0] if isinstance(indicator_data, list) else indicator_data
sma_values = indicator_info["data"]["values"]
# Konversi menjadi DataFrame
df_analysis = pd.DataFrame({
"SMA": pd.to_numeric(pd.Series(sma_values), errors="coerce")
})
df_analysis = df_analysis.dropna().reset_index(drop=True)
# Hitung perubahan SMA
df_analysis["SMA_Change"] = df_analysis["SMA"].diff()
# Hitung arah tren
df_analysis["Trend"] = np.where(
df_analysis["SMA_Change"] > 0, "UP",
np.where(df_analysis["SMA_Change"] < 0, "DOWN", "FLAT")
)
# Ambil data terbaru
latest_sma = df_analysis["SMA"].iloc[-1]
previous_sma = df_analysis["SMA"].iloc[-2]
# Perbandingan SMA dengan VWAP
distance = ((latest_sma - vwap_value) / vwap_value) * 100
print("========== BTC MARKET DATA ==========")
print("Symbol :", SYMBOL)
print("VWAP :", vwap_value)
print("Total Volume :", total_volume)
print("Latest SMA :", latest_sma)
print("Previous SMA :", previous_sma)
print("SMA Difference :", latest_sma - previous_sma)
print("SMA vs VWAP (%) :", round(distance, 4))
print("\n========== SMA HISTORY ==========")
display(df_analysis.tail(10))
# Visualisasi
plt.figure(figsize=(14, 6))
plt.plot(df_analysis["SMA"], label="SMA 14")
plt.axhline(vwap_value, linestyle="--", label="VWAP")
plt.title("BTC SMA vs VWAP")
plt.xlabel("Observation")
plt.ylabel("Value")
plt.legend()
plt.grid(alpha=0.3)
plt.show()Cell 5: BTC Trading Decision Analysis
Purpose
The fifth cell completes the BTC Trading Analysis by combining SMA momentum and the latest SMA position relative to VWAP to produce a rule-based trading classification.
SMA momentum is calculated as the percentage change between the latest and previous SMA values:
\[ SMA\ Momentum(\%) = \frac{Latest\ SMA - Previous\ SMA}{Previous\ SMA} \times 100 \]
The market position is classified as ABOVE VWAP, BELOW VWAP, or AT VWAP. Momentum is classified as RISING, FALLING, or FLAT.
The signal rules implemented in the code are:
SMA position relative to VWAP | SMA momentum | Signal |
|---|---|---|
Above VWAP | Positive | BULLISH |
Below VWAP | Negative | BEARISH |
Any other combination | Any other combination | NEUTRAL |
The cell creates a result table containing the symbol, VWAP, latest and previous SMA, market position, momentum status, SMA momentum percentage, SMA–VWAP distance, trading signal, and interpretation.
It then produces two visualizations: an SMA-versus-VWAP chart and an SMA momentum chart with a zero reference line. Finally, it exports BTC_SMA_History.csv and BTC_Trading_Analysis.csv, then prints the final signal and interpretation.
Complete code:
"""CELL 5.BTC Trading Decision Analysis"""
# ==========================================
# CELL 5 — BTC TRADING DECISION ANALYSIS
# ==========================================
# 1. MENGHITUNG MOMENTUM SMA
sma_momentum = (
(latest_sma - previous_sma) / previous_sma
) * 100
# 2. MENENTUKAN POSISI SMA TERHADAP VWAP
if latest_sma > vwap_value:
market_position = "ABOVE VWAP"
elif latest_sma < vwap_value:
market_position = "BELOW VWAP"
else:
market_position = "AT VWAP"
# 3. MENENTUKAN ARAH MOMENTUM
if sma_momentum > 0:
momentum_status = "RISING"
elif sma_momentum < 0:
momentum_status = "FALLING"
else:
momentum_status = "FLAT"
# 4. MENENTUKAN SINYAL TRADING
if latest_sma > vwap_value and sma_momentum > 0:
signal = "BULLISH"
explanation = "SMA berada di atas VWAP dan momentum meningkat."
elif latest_sma < vwap_value and sma_momentum < 0:
signal = "BEARISH"
explanation = "SMA berada di bawah VWAP dan momentum menurun."
else:
signal = "NEUTRAL"
explanation = "Belum ada keselarasan posisi dan momentum SMA."
# 5. MEMBUAT TABEL ANALISIS
result = pd.DataFrame({
"Metric": [
"Symbol",
"VWAP",
"Latest SMA",
"Previous SMA",
"Market Position",
"Momentum Status",
"SMA Momentum (%)",
"SMA vs VWAP (%)",
"Trading Signal",
"Interpretation"
],
"Value": [
SYMBOL,
vwap_value,
latest_sma,
previous_sma,
market_position,
momentum_status,
round(sma_momentum, 5),
round(distance, 5),
signal,
explanation
]
})
# 6. MENAMPILKAN HASIL
print("=" * 55)
print(" BTC TRADING DECISION ANALYSIS")
print("=" * 55)
display(result)
# 7. VISUALISASI SMA DAN VWAP
plt.figure(figsize=(14, 6))
plt.plot(
df_analysis["SMA"],
label="SMA 14",
linewidth=2
)
plt.axhline(
y=vwap_value,
linestyle="--",
label="VWAP"
)
plt.title("BTC SMA vs VWAP Analysis")
plt.xlabel("Observation")
plt.ylabel("Value")
plt.legend()
plt.grid(alpha=0.3)
plt.show()
# 8. VISUALISASI MOMENTUM
plt.figure(figsize=(14, 4))
plt.plot(
df_analysis["SMA_Change"],
label="SMA Momentum"
)
plt.axhline(y=0, linestyle="--")
plt.title("BTC SMA Momentum Analysis")
plt.xlabel("Observation")
plt.ylabel("SMA Change")
plt.legend()
plt.grid(alpha=0.3)
plt.show()
# 9. EXPORT HASIL ANALISIS
df_analysis.to_csv(
"BTC_SMA_History.csv",
index=False
)
result.to_csv(
"BTC_Trading_Analysis.csv",
index=False
)
print("\nANALYSIS COMPLETED")
print("Trading Signal:", signal)
print("Interpretation:", explanation)
print("\nFiles exported:")
print("1. BTC_SMA_History.csv")
print("2. BTC_Trading_Analysis.csv")Result:

3. Conclusion
This article has demonstrated BTC Trading Analysis with SMA and VWAP through a Python workflow connected to the MarketFlow All-in-One Market Finance API. The implementation retrieves SMA information for BTC and VWAP information for BTCUSDT, processes the returned data, calculates SMA changes and momentum, compares the latest SMA with VWAP, and produces a rule-based market classification.
The five-cell workflow covers library configuration, API data retrieval, data processing, visualization, decision logic, and CSV export. Its BULLISH, BEARISH, and NEUTRAL labels make the implemented conditions transparent and reproducible. The accompanying charts and exported CSV files provide a practical way to inspect the indicator history and the resulting analysis.
The system should be understood as a descriptive technical decision-support tool rather than a predictive model or a complete trading strategy. The source code does not perform backtesting, calculate strategy profitability, evaluate transaction costs, or submit trading orders. The interpretation of the output also depends on the accuracy and time-window consistency of the data returned by the API.
Further development could include validation that SMA and VWAP use compatible data intervals, historical backtesting, additional technical and liquidity indicators, and explicit risk-management rules. These additions would help evaluate the reliability and practical usefulness of the rule-based classification.
