Financial markets are characterized by continuous price movements influenced by economic conditions, monetary policies, geopolitical developments, investor sentiment, and changes in global liquidity. These factors create challenges for traders who need to interpret market conditions and identify potential trading opportunities.
Gold, commonly represented by the XAUUSD trading symbol, is one of the financial instruments frequently monitored by traders. Its price movements are influenced by several factors, including US dollar strength, interest rate expectations, inflation developments, and global economic uncertainty.
Technical analysis provides a systematic approach to examining historical price movements and identifying potential market trends, momentum conditions, and volatility characteristics. Through mathematical indicators, traders can evaluate market conditions without relying exclusively on subjective chart interpretation.
Several technical indicators are commonly used in financial market analysis.
Moving averages help identify the general direction of price movements. Momentum indicators such as the Relative Strength Index (RSI) provide information about the strength of price movements. Meanwhile, the Moving Average Convergence Divergence (MACD) evaluates relationships between short-term and long-term exponential moving averages.
Volatility indicators are also important in trading analysis. Bollinger Bands provide information about price dispersion relative to a moving average, while the Average True Range (ATR) measures market volatility and can be incorporated into stop-loss and take-profit calculations.
However, analyzing multiple indicators independently can make trading decisions complicated. A structured analytical framework is therefore useful for integrating several technical indicators into one computational environment.
Python provides an effective environment for developing automated financial analysis systems. Libraries such as Requests, Pandas, NumPy, and Plotly enable financial data retrieval, numerical calculations, data transformation, and interactive visualization.
This article presents the MarketFlow Trading Analyzer, a Python-based trading analysis framework developed using the MarketFlow All-in-One Market Finance API through RapidAPI.
The system retrieves XAUUSD historical price information through the /v2/chart/price endpoint using the following configuration:
Symbol:
OANDA:XAUUSD.Timeframe:
D(Daily).Candle range: 100.
Timezone:
Asia/Jakarta.
The framework also retrieves trending market information through the /trending endpoint.
The primary analytical objective is to develop an integrated trading intelligence workflow that combines historical price analysis, technical indicator calculations, rule-based signal generation, and risk management.
The analytical workflow consists of five computational cells:
API configuration, library installation, and trading parameter initialization.
Historical market data extraction and trending market retrieval.
Technical indicator calculation and trading signal generation.
Interactive trading dashboard visualization.
Trending market analysis and consolidated trader report generation.
The system produces BUY, SELL, or WAIT signals based on predefined technical conditions. These signals are accompanied by entry price, stop-loss, take-profit, and estimated position sizing calculations when applicable.
An important distinction is that the system functions as a rule-based technical analysis framework rather than a fully automated trading execution bot. It generates analytical signals but does not directly submit orders to a broker or execute live transactions.
2. Methodology
The MarketFlow Trading Analyzer is organized into five computational cells. Each cell performs a specific function within the market data collection, technical analysis, signal generation, visualization, and reporting workflow.
Cell | Main Function |
|---|---|
Cell 1 | Library installation, API authentication, market configuration, and money management parameters. |
Cell 2 | XAUUSD historical price extraction, trending market retrieval, and OHLC data normalization. |
Cell 3 | EMA, RSI, MACD, Bollinger Bands, ATR calculations, trading signal generation, and risk management. |
Cell 4 | Interactive Plotly dashboard visualization. |
Cell 5 | Trending market extraction and consolidated professional trader report generation. |
2.1. System Configuration and API Authentication
The first computational cell establishes the analytical environment and API authentication.
The framework uses Requests for HTTP communication, Pandas for financial data processing, NumPy for numerical calculations, Plotly Graph Objects for interactive visualization, Plotly Express for graphical analysis, and JSON for handling API responses.
The API host is configured as:
marketflow-all-in-one-market-finance-api.p.rapidapi.com
The API authentication process uses a RapidAPI key entered through Python's getpass() function. This approach prevents the API key from being directly displayed in the notebook output.
The market configuration establishes XAUUSD as the primary financial instrument.
The following parameters are implemented:
Parameter | Configuration |
|---|---|
Market Symbol | OANDA:XAUUSD |
Timeframe | Daily |
Candle Range | 100 |
Timezone | Asia/Jakarta |
Account Balance | USD 10,000 |
Risk Percentage | 1% |
Risk-Reward Ratio | 1:2 |
The money management configuration determines the maximum monetary risk allocated to a trading position.
The risk capital is calculated using:
[
Risk\ Capital = Account\ Balance \times \frac{Risk\ Percentage}{100}
]
With the configured account balance and risk percentage:
[
Risk\ Capital = 10,000 \times \frac{1}{100}
]
[
Risk\ Capital = USD\ 100
]
Therefore, the framework allocates USD 100 as the configured monetary risk for each eligible trading setup.
Code — Cell 1: Configuration and Libraries
# ============================================================
# MARKETFLOW TRADING ANALYZER
# CELL 1: SETUP & API CONFIGURATION
# ============================================================
!pip -q install requests pandas numpy matplotlib plotly
import requests
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
import warnings
import json
import getpass
from plotly.subplots import make_subplots
from IPython.display import display, Markdown
warnings.filterwarnings("ignore")
# API CONFIGURATION
API_HOST = "marketflow-all-in-one-market-finance-api.p.rapidapi.com"
BASE_URL = f"https://{API_HOST}"
API_KEY = getpass.getpass("Enter RapidAPI Key: ")
HEADERS = {
"x-rapidapi-key": API_KEY,
"x-rapidapi-host": API_HOST
}
# MARKET CONFIGURATION
SYMBOL = "OANDA:XAUUSD"
TIMEFRAME = "D"
CANDLE_RANGE = 100
TIMEZONE = "Asia/Jakarta"
# MONEY MANAGEMENT
ACCOUNT_BALANCE = 10000
RISK_PERCENT = 1.0
RISK_REWARD = 2.02.2. Financial Market Data Collection Through MarketFlow API
The second computational cell retrieves historical XAUUSD price information and trending market data through the MarketFlow API.
The framework implements an API request function named api_get() to manage HTTP communication.
The function accepts an endpoint and optional parameters, sends an HTTP GET request, validates the response status, and returns the retrieved JSON data.
The first dataset is obtained through the /v2/chart/price endpoint.
The request uses four parameters:
range: Number of requested historical candlesticks.timeframe: Selected chart timeframe.timezone: Timezone used for market date conversion.symbol: Requested financial instrument.
The second dataset is obtained through the /trending endpoint.
This dataset provides additional information about financial instruments identified by the API as trending.
OHLC Data Extraction
The historical price response is processed through a recursive function named extract_ohlc().
The function searches nested JSON structures to identify Open, High, Low, and Close information.
The framework supports two data structures:
A list containing dictionary-based OHLC records.
A nested response containing timestamps and quote information.
The extracted records are subsequently converted into a Pandas DataFrame.
The system identifies the timestamp field and converts numerical price fields into appropriate numeric formats.
Timestamp conversion considers whether the original values are expressed in seconds or milliseconds.
The resulting date information is converted into the configured Asia/Jakarta timezone when the timestamp is numerical.
The dataset is then sorted chronologically, duplicate dates are removed, and incomplete OHLC observations are excluded.
The system also performs a minimum data validation check. If fewer than 30 valid candlesticks are available, the program stops the analysis.
This validation helps ensure that the dataset contains a minimum number of observations before technical calculations are performed.
Code — Cell 2: Market Data Extraction
# ============================================================
# CELL 2: MARKET DATA & TRENDING
# ============================================================
def api_get(endpoint, params=None):
url = BASE_URL + endpoint
response = requests.get(
url,
headers=HEADERS,
params=params,
timeout=30
)
response.raise_for_status()
return response.json()
# GET XAUUSD PRICE DATA
price_data = api_get(
"/v2/chart/price",
{
"range": CANDLE_RANGE,
"timeframe": TIMEFRAME,
"timezone": TIMEZONE,
"symbol": SYMBOL
}
)
# GET TRENDING DATA
trending_data = api_get("/trending")
# EXTRACT OHLC DATA
records = extract_ohlc(price_data)
if not records:
raise ValueError(
"OHLC data format is not recognized."
)
df = pd.DataFrame(records)
# NORMALIZE PRICE DATA
df.columns = [
str(c).lower() for c in df.columns
]
# CONVERT NUMERICAL VALUES
for col in ["open", "high", "low", "close"]:
df[col] = pd.to_numeric(
df[col],
errors="coerce"
)
# SORT AND CLEAN DATA
df = (
df.dropna(
subset=["date", "open", "high", "low", "close"]
)
.sort_values("date")
.drop_duplicates("date")
.set_index("date")
)
if len(df) < 30:
raise ValueError(
"Insufficient market candle data."
)2.3. Technical Indicator Calculation
The third computational cell represents the primary analytical engine of the framework.
The system calculates six technical analysis components:
Exponential Moving Average.
Relative Strength Index.
Moving Average Convergence Divergence.
Bollinger Bands.
Average True Range.
Volume Moving Average.
These indicators are calculated using historical OHLC price information retrieved from the API.
A. Exponential Moving Average (EMA)
The Exponential Moving Average is used to evaluate price trends by assigning greater weight to recent observations.
The framework calculates three EMA periods:
EMA 20.
EMA 50.
EMA 200.
The general EMA calculation is:
[
EMA_t = \alpha P_t+(1-\alpha)EMA_{t-1}
]
Where:
(EMA_t) = Current exponential moving average.
(P_t) = Current closing price.
(\alpha) = Smoothing factor.
(EMA_{t-1}) = Previous EMA value.
The smoothing factor is calculated as:
[
\alpha=\frac{2}{N+1}
]
Where (N) represents the selected period.
The three EMA indicators provide different perspectives on price movements.
Indicator | Analytical Purpose |
|---|---|
EMA 20 | Short-term price trend. |
EMA 50 | Medium-term price trend. |
EMA 200 | Longer-term price trend. |
The relationship between EMA 20 and EMA 50 is incorporated into the trading signal scoring mechanism.
EMA 200 is calculated and displayed as an additional trend reference but is not directly included in the BUY/SELL scoring conditions.
B. Relative Strength Index (RSI 14)
The Relative Strength Index evaluates the magnitude of recent upward and downward price movements.
The framework calculates RSI using a 14-period exponentially weighted average of gains and losses.
The calculation begins with the closing price difference:
[
\Delta P_t=P_t-P_{t-1}
]
Positive price changes are classified as gains, while negative price changes are classified as losses.
The relative strength is calculated as:
[
RS=\frac{Average\ Gain}{Average\ Loss}
]
The RSI formula is:
[
RSI=100-\frac{100}{1+RS}
]
The system implements the following RSI conditions:
RSI Condition | Interpretation |
|---|---|
Above 70 | Upper momentum zone. |
50–70 | Positive momentum zone used for BUY scoring. |
30–50 | Negative momentum zone used for SELL scoring. |
Below 30 | Lower momentum zone. |
The RSI indicator contributes to the signal scoring mechanism when its value falls within the configured positive or negative momentum intervals.
C. Moving Average Convergence Divergence (MACD)
The MACD indicator evaluates the relationship between two exponential moving averages.
The framework uses the conventional 12, 26, and 9-period configuration.
The MACD line is calculated using:
[
MACD=EMA_{12}-EMA_{26}
]
The signal line is calculated as:
[
Signal=EMA_9(MACD)
]
The MACD histogram represents the difference between the MACD line and the signal line:
[
Histogram=MACD-Signal
]
The framework evaluates the relationship between the MACD line and its signal line.
MACD above Signal contributes to BUY scoring.
MACD below Signal contributes to SELL scoring.
D. Bollinger Bands
Bollinger Bands measure price dispersion around a moving average.
The framework calculates the upper and lower bands using a 20-period simple moving average and two standard deviations.
The middle band is:
[
MB=SMA_{20}
]
The upper band is:
[
UB=SMA_{20}+2\sigma
]
The lower band is:
[
LB=SMA_{20}-2\sigma
]
Where:
(MB) = Middle Band.
(UB) = Upper Band.
(LB) = Lower Band.
(\sigma) = Rolling standard deviation.
The bands provide a visual representation of price volatility and relative price positioning.
In the current implementation, Bollinger Bands are displayed in the dashboard but are not directly included in the trading signal scoring conditions.
E. Average True Range (ATR 14)
Average True Range measures market volatility by examining the range of price movements.
The True Range is calculated as the maximum of three values:
[
TR=\max
\begin{cases}
High-Low\
|High-Previous\ Close|\
|Low-Previous\ Close|
\end{cases}
]
The framework subsequently calculates ATR using a 14-period exponentially weighted moving average:
[
ATR_t=\frac{1}{14}TR_t+\frac{13}{14}ATR_{t-1}
]
ATR is particularly important in this framework because it determines the distance between the entry price and the stop-loss level.
A higher ATR produces a wider stop-loss distance, while a lower ATR produces a narrower stop-loss distance.
F. Volume Moving Average
The framework calculates a 20-period volume moving average when volume information is available.
[
VOL_MA20=SMA(Volume,20)
]
This indicator provides an additional reference for examining volume behavior.
However, volume moving average is not directly incorporated into the BUY/SELL signal scoring mechanism.
Code — Cell 3: Technical Indicator Calculation
# ============================================================
# CELL 3: TECHNICAL ANALYSIS ENGINE
# ============================================================
# EMA
df["EMA20"] = df["close"].ewm(
span=20,
adjust=False
).mean()
df["EMA50"] = df["close"].ewm(
span=50,
adjust=False
).mean()
df["EMA200"] = df["close"].ewm(
span=200,
adjust=False
).mean()
# RSI
delta = df["close"].diff()
gain = delta.clip(lower=0)
loss = -delta.clip(upper=0)
avg_gain = gain.ewm(
alpha=1/14,
adjust=False
).mean()
avg_loss = loss.ewm(
alpha=1/14,
adjust=False
).mean()
rs = avg_gain / avg_loss.replace(0, np.nan)
df["RSI"] = 100 - (100 / (1 + rs))
# MACD
ema12 = df["close"].ewm(
span=12,
adjust=False
).mean()
ema26 = df["close"].ewm(
span=26,
adjust=False
).mean()
df["MACD"] = ema12 - ema26
df["MACD_SIGNAL"] = df["MACD"].ewm(
span=9,
adjust=False
).mean()
df["MACD_HIST"] = (
df["MACD"] - df["MACD_SIGNAL"]
)
# BOLLINGER BANDS
middle = df["close"].rolling(20).mean()
std = df["close"].rolling(20).std()
df["BB_UPPER"] = middle + 2 * std
df["BB_LOWER"] = middle - 2 * std
# ATR
prev_close = df["close"].shift(1)
tr = pd.concat([
df["high"] - df["low"],
abs(df["high"] - prev_close),
abs(df["low"] - prev_close)
], axis=1).max(axis=1)
df["ATR"] = tr.ewm(
alpha=1/14,
adjust=False
).mean()
# VOLUME MOVING AVERAGE
df["VOL_MA20"] = df["volume"].rolling(20).mean()2.4. Automated Trading Signal Generation
After calculating the technical indicators, the framework generates trading signals using a rule-based scoring mechanism.
The system evaluates four technical conditions to determine the relative strength of BUY and SELL opportunities.
Each qualifying condition contributes one point to the corresponding signal score.
A. BUY Signal Conditions
The BUY scoring mechanism evaluates the following conditions:
No. | Technical Condition | Score |
|---|---|---|
1 | Closing price is above EMA 20. | +1 BUY |
2 | EMA 20 is above EMA 50. | +1 BUY |
3 | MACD is above MACD Signal. | +1 BUY |
4 | RSI is between 50 and 70. | +1 BUY |
The total BUY score is calculated by adding the points from all qualifying conditions.
B. SELL Signal Conditions
The SELL scoring mechanism uses the following conditions:
No. | Technical Condition | Score |
|---|---|---|
1 | Closing price is below EMA 20. | +1 SELL |
2 | EMA 20 is below EMA 50. | +1 SELL |
3 | MACD is below MACD Signal. | +1 SELL |
4 | RSI is between 30 and 50. | +1 SELL |
The system subsequently compares the BUY and SELL scores.
C. Trading Decision Classification
The framework uses the following decision rules:
Condition | Trading Decision |
|---|---|
BUY score is at least 3 and greater than SELL score. | BUY |
SELL score is at least 3 and greater than BUY score. | SELL |
Neither condition is satisfied. | WAIT |
The WAIT classification indicates that the available technical conditions do not satisfy the minimum requirements established by the framework.
This scoring approach combines trend direction, moving average relationships, MACD momentum, and RSI conditions into a single decision mechanism.
It should be emphasized that the resulting signals represent predefined technical conditions rather than statistically validated predictions of future price movements.
2.5. Entry Price, Stop-Loss, Take-Profit, and Position Sizing
The fifth analytical component within the technical analysis engine calculates trading parameters when a BUY or SELL signal is generated.
The latest closing price is used as the reference entry price.
The ATR indicator determines the stop-loss distance.
The framework uses an ATR multiplier of 1.5 and a configured risk-reward ratio of 1:2.
A. Entry Price
The entry price is defined as:
[
Entry=Latest\ Closing\ Price
]
B. BUY Stop-Loss and Take-Profit
For a BUY signal, the stop-loss is placed below the entry price.
[
SL=Entry-(ATR\times1.5)
]
The take-profit level is calculated as:
[
TP=Entry+(ATR\times1.5\times2)
]
Therefore:
[
TP=Entry+(ATR\times3)
]
C. SELL Stop-Loss and Take-Profit
For a SELL signal, the stop-loss is placed above the entry price.
[
SL=Entry+(ATR\times1.5)
]
The take-profit level is:
[
TP=Entry-(ATR\times1.5\times2)
]
These formulas maintain a configured 1:2 relationship between the stop-loss distance and take-profit distance.
D. Risk Capital Calculation
The maximum monetary risk is calculated using:
[
Risk\ Money=Account\ Balance\times
\frac{Risk\ Percentage}{100}
]
With the configured parameters:
[
Risk\ Money=10,000\times1%=USD\ 100
]
E. Estimated Position Size
The framework estimates position size using:
[
Estimated\ Units=
\frac{Risk\ Money}{|Entry-Stop\ Loss|}
]
This calculation provides a simplified estimate of position size based on price distance.
Actual tradable lot size must also consider broker-specific contract specifications, tick value, currency conversion, minimum volume, and execution costs. Consequently, the calculated units should not automatically be treated as a broker-ready order quantity.
When the signal is WAIT, stop-loss, take-profit, and estimated position size are assigned unavailable numerical values.
Code — Cell 3: Trading Signal and Risk Calculation
# SIGNAL SCORING
buy_score = 0
sell_score = 0
if last["close"] > last["EMA20"]:
buy_score += 1
else:
sell_score += 1
if last["EMA20"] > last["EMA50"]:
buy_score += 1
else:
sell_score += 1
if last["MACD"] > last["MACD_SIGNAL"]:
buy_score += 1
else:
sell_score += 1
if 50 < last["RSI"] < 70:
buy_score += 1
if 30 < last["RSI"] < 50:
sell_score += 1
# MARKET DECISION
if buy_score >= 3 and buy_score > sell_score:
signal = "BUY"
elif sell_score >= 3 and sell_score > buy_score:
signal = "SELL"
else:
signal = "WAIT"
# ENTRY & RISK CALCULATION
entry = float(last["close"])
atr = float(last["ATR"])
if signal == "BUY":
stop_loss = entry - (atr * 1.5)
take_profit = (
entry + (atr * 1.5 * RISK_REWARD)
)
elif signal == "SELL":
stop_loss = entry + (atr * 1.5)
take_profit = (
entry - (atr * 1.5 * RISK_REWARD)
)
else:
stop_loss = np.nan
take_profit = np.nan
risk_money = (
ACCOUNT_BALANCE * RISK_PERCENT / 100
)
risk_distance = (
abs(entry - stop_loss)
if np.isfinite(stop_loss)
else np.nan
)
estimated_units = (
risk_money / risk_distance
if np.isfinite(risk_distance)
and risk_distance > 0
else np.nan
)2.6. Trending Market Analysis
In addition to XAUUSD historical price analysis, the framework retrieves trending market information through the /trending endpoint.
The retrieved JSON response may contain nested lists and dictionaries.
To process this information, the system implements a recursive function named extract_trending().
The function examines each dictionary and searches for records containing at least one asset identification field.
The identification fields include:
Symbol.
Ticker.
Name.
Coin.
Asset.
The extracted records are converted into a Pandas DataFrame.
Duplicate records are removed before the system displays the first 20 observations.
If the API response does not contain a recognizable trending structure, the framework displays a message and provides a portion of the original JSON response for further examination.
This module provides additional market information alongside the primary XAUUSD technical analysis.
However, the current implementation does not calculate a separate ranking score, trend direction, or correlation between the trending instruments and XAUUSD.
3. Results and Discussion
3.1. Market Data Collection Results
The MarketFlow Trading Analyzer retrieves two categories of financial information through the MarketFlow API.
The first dataset consists of historical XAUUSD price information obtained through the /v2/chart/price endpoint.
The second dataset contains trending market information retrieved through the /trending endpoint.
The XAUUSD request uses OANDA:XAUUSD as the requested symbol, a daily timeframe, and a configured historical range of 100 candlesticks.
The retrieved price information is processed into a structured DataFrame containing Open, High, Low, Close, and Volume fields when volume is available.
The framework also converts timestamps into the configured Jakarta timezone.
This normalization process establishes a consistent chronological dataset for subsequent technical indicator calculations.
The actual number of valid observations depends on the API response, data availability, and the OHLC validation process. The configured range of 100 candles should therefore not be interpreted as a guarantee that exactly 100 valid records will be returned.
3.2. Technical Indicator Analysis Results
The technical analysis module calculates several indicators to evaluate different characteristics of XAUUSD price movements.
The EMA indicators provide information about the relationship between short-term, medium-term, and longer-term price trends.
EMA 20 and EMA 50 are particularly important because their relationship contributes directly to the BUY and SELL scoring mechanism.
Meanwhile, EMA 200 provides an additional long-term trend reference.
The RSI indicator evaluates momentum conditions, while MACD identifies the relationship between short-term and long-term exponential moving averages.
Bollinger Bands provide a visual representation of price dispersion, and ATR measures market volatility.
The integration of these indicators enables the framework to examine price behavior from multiple analytical perspectives.
An important implementation detail is that EMA 200, Bollinger Bands, and Volume Moving Average are calculated for analytical visualization but do not directly contribute to the current trading signal score.
Because the dataset is configured for 100 candlesticks, the EMA 200 calculation does not contain 200 historical observations. Its values therefore represent an EMA calculated from the available sample rather than a fully established 200-period historical reference.
3.3. Automated Trading Signal Results
The automated signal module combines four technical conditions into a rule-based scoring system.
The BUY score increases when the closing price is above EMA 20, EMA 20 is above EMA 50, MACD is above its signal line, and RSI falls between 50 and 70.
The SELL score increases when the closing price is below EMA 20, EMA 20 is below EMA 50, MACD is below its signal line, and RSI falls between 30 and 50.
The framework subsequently evaluates the scores and generates one of three classifications:
BUY.
SELL.
WAIT.
The BUY and SELL classifications require a minimum score of three and must exceed the opposing score.
Otherwise, the framework produces a WAIT signal.
This mechanism provides a structured interpretation of the latest available technical conditions.
The system does not use backtesting or historical signal performance evaluation in its current implementation. Therefore, the generated signals should be interpreted as current rule-based analytical outputs rather than evidence of historical trading profitability.
3.4. Risk Management Analysis Results
The risk management module integrates ATR-based stop-loss and take-profit calculations with a predefined account risk configuration.
The configured account balance is USD 10,000, with a 1% risk allocation.
Consequently, the framework calculates a nominal risk capital of USD 100 for each eligible trading setup.
The ATR indicator determines the distance between the entry price and stop-loss level.
For BUY signals, the stop-loss is positioned below the entry price, while the take-profit is positioned above it.
For SELL signals, the stop-loss is positioned above the entry price, while the take-profit is positioned below it.
The framework uses an ATR multiplier of 1.5 and a risk-reward ratio of 1:2.
This approach allows stop-loss and take-profit levels to adapt to the volatility observed in the historical price data.
However, the estimated position size is based on a simplified price-distance calculation. Actual trading risk may differ because of contract specifications, spread, slippage, commissions, and other broker execution conditions.
3.5. Interactive Trading Dashboard Visualization
The fourth computational cell generates an interactive trading dashboard using Plotly.
The dashboard consists of three vertically arranged analytical panels.
1. XAUUSD Price Action
The first panel displays historical XAUUSD candlesticks.
The visualization includes:
Open, High, Low, and Close prices.
EMA 20.
EMA 50.
EMA 200.
Upper Bollinger Band.
Lower Bollinger Band.
This panel provides a comprehensive overview of price movements and the relationship between market prices and technical trend indicators.
2. RSI Momentum
The second panel displays the RSI 14 indicator.
Two horizontal reference lines are added at 70 and 30.
These reference levels help identify upper and lower RSI zones.
The visualization supports the examination of momentum conditions within the selected historical period.
3. MACD Trend
The third panel displays:
MACD line.
MACD signal line.
MACD histogram.
The visualization allows traders to examine the relationship between the MACD line and signal line, as well as the difference between the two values.
The dashboard uses the plotly_dark template, a unified hover mode, and a horizontal legend.
Its layout is configured with a height of 950 pixels to accommodate the three analytical panels.
The resulting dashboard is interactive, allowing users to inspect individual observations through cursor-based data information and explore historical price movements.
The dashboard is displayed through fig.show() in the notebook environment.
In addition, the framework exports the processed technical analysis dataset into:
XAUUSD_Trading_Analysis.csv
This CSV file contains historical price information and the calculated technical indicators.
Code — Cell 4: Interactive Trading Dashboard
# ============================================================
# CELL 4: TRADING DASHBOARD
# ============================================================
fig = make_subplots(
rows=3,
cols=1,
shared_xaxes=True,
vertical_spacing=0.04,
row_heights=[0.60, 0.20, 0.20],
subplot_titles=(
"XAUUSD PRICE ACTION",
"RSI MOMENTUM",
"MACD TREND"
)
)
# CANDLESTICK
fig.add_trace(
go.Candlestick(
x=df.index,
open=df["open"],
high=df["high"],
low=df["low"],
close=df["close"],
name="XAUUSD"
),
row=1,
col=1
)
# EMA
for col, color in [
("EMA20", "orange"),
("EMA50", "blue"),
("EMA200", "purple")
]:
fig.add_trace(
go.Scatter(
x=df.index,
y=df[col],
name=col,
line=dict(width=1.5, color=color)
),
row=1,
col=1
)
# RSI
fig.add_trace(
go.Scatter(
x=df.index,
y=df["RSI"],
name="RSI"
),
row=2,
col=1
)
fig.add_hline(
y=70,
line_dash="dash",
line_color="red",
row=2,
col=1
)
fig.add_hline(
y=30,
line_dash="dash",
line_color="green",
row=2,
col=1
)
# MACD
fig.add_trace(
go.Scatter(
x=df.index,
y=df["MACD"],
name="MACD"
),
row=3,
col=1
)
fig.add_trace(
go.Scatter(
x=df.index,
y=df["MACD_SIGNAL"],
name="Signal"
),
row=3,
col=1
)
fig.add_trace(
go.Bar(
x=df.index,
y=df["MACD_HIST"],
name="MACD Histogram",
opacity=0.35
),
row=3,
col=1
)
fig.update_layout(
title=f"MARKETFLOW TRADER DASHBOARD | {SYMBOL} | {signal}",
template="plotly_dark",
height=950,
xaxis_rangeslider_visible=False,
hovermode="x unified",
legend=dict(orientation="h")
)
fig.show()
# SAVE DATA
df.to_csv("XAUUSD_Trading_Analysis.csv")Result:
![]() | ||
|---|---|---|
3.6. Trending Market and Trader Report Results
The fifth computational cell combines trending market extraction with the final trader report.
The trending module identifies asset records from the API response and displays up to 20 observations.
The final trader report consolidates the most important analytical information into a structured text output.
The report includes:
Information | Description |
|---|---|
Symbol | Requested financial instrument. |
Timeframe | Selected chart timeframe. |
Last Candle | Timestamp of the latest valid observation. |
Current Price | Latest closing price. |
EMA 20 | Short-term trend reference. |
EMA 50 | Medium-term trend reference. |
EMA 200 | Longer-term trend reference. |
RSI | Momentum measurement. |
MACD | MACD indicator value. |
ATR | Volatility measurement. |
BUY Score | Total qualifying BUY conditions. |
SELL Score | Total qualifying SELL conditions. |
Trading Signal | BUY, SELL, or WAIT classification. |
Entry | Reference entry price. |
Stop Loss | Calculated stop-loss level. |
Take Profit | Calculated take-profit level. |
Risk Capital | Configured monetary risk. |
Estimated Units | Simplified position size estimate. |
Trend Analysis | Bullish, Bearish, or Sideways/Mixed. |
The final trend classification uses the relationship between the latest closing price, EMA 20, and EMA 50.
The system identifies a BULLISH trend when:
[
Close>EMA20>EMA50
]
A BEARISH trend is identified when:
[
Close<EMA20<EMA50
]
If neither condition is satisfied, the framework classifies the market as SIDEWAYS / MIXED.
This classification is independent of the BUY/SELL scoring result. Therefore, the final trend description and trading signal may provide different analytical perspectives.
The report also includes trader notes concerning fundamental market conditions, higher-timeframe confirmation, broker spread, slippage, and risk control.
Finally, a disclaimer explains that technical analysis results are not guarantees of profitability or direct investment recommendations.
3.7. Consolidated Trading Intelligence Outputs
The framework produces several analytical outputs that support further examination of the XAUUSD market.
Output | Description |
|---|---|
| Historical XAUUSD data and calculated technical indicators. |
Interactive Plotly Dashboard | Three-panel visualization of price action, RSI, and MACD. |
Technical Analysis Summary | Latest technical indicator values and trading scores. |
Trending Market DataFrame | Extracted trending market records. |
Professional Trader Report | Consolidated market conditions, trading signal, and risk parameters. |
The framework combines numerical analysis, interactive visualization, and textual reporting within a single Python environment.
The CSV output can be opened through Microsoft Excel or other data analysis applications.
The interactive dashboard is displayed within the notebook environment, while the trader report provides a concise summary of the latest analytical results.
Unlike a fully automated trading platform, the current implementation does not export a separate HTML dashboard or PDF report, and it does not automatically execute transactions.
3.8. Analytical Limitations and Future Improvements
Several limitations should be considered when interpreting the analytical outputs.
First, the analysis depends on the availability and quality of API data. Incomplete or incorrectly structured market responses may affect OHLC extraction and subsequent calculations.
Second, the configured historical range is 100 candlesticks. Although the system calculates EMA 200, the available dataset does not provide a full 200-period historical warm-up. A larger historical dataset would improve the reliability of longer-period EMA initialization.
Third, the trading signal mechanism uses fixed technical conditions. The scoring system does not automatically adapt its thresholds to different market regimes, volatility conditions, or macroeconomic developments.
Fourth, Bollinger Bands and EMA 200 are not included in the current signal scoring mechanism. They serve as additional visual and analytical references rather than direct decision inputs.
Fifth, the framework does not implement historical backtesting. Consequently, it does not provide verified win rates, profit factors, maximum drawdown, or historical trading performance.
Sixth, the position sizing calculation is simplified. The estimated units are calculated using price distance without incorporating broker-specific contract specifications, tick value, lot conversion, commissions, or execution costs.
Seventh, the trending market module focuses on record extraction. It does not yet perform independent ranking, sector classification, or correlation analysis.
Eighth, the current implementation uses the latest available closing observation as the reference entry price. This does not guarantee that an order could be executed at the same price in a live market.
Future improvements could include:
Historical backtesting and performance evaluation.
Walk-forward testing and out-of-sample validation.
Higher-timeframe trend confirmation.
Dynamic ATR-based position sizing.
Broker-specific lot and contract calculations.
Automated economic calendar integration.
Gold and US Dollar correlation analysis.
Fundamental market sentiment integration.
Advanced volatility regime classification.
Multi-timeframe RSI and MACD analysis.
Interactive BUY/SELL signal markers.
Automated HTML dashboard export.
Historical trading performance reports.
Real-time market monitoring.
Broker API integration for order execution.
These developments could expand the framework into a more comprehensive trading intelligence platform.
4. Conclusion
This article presents the MarketFlow Trading Analyzer, a Python-based technical analysis framework developed using the MarketFlow All-in-One Market Finance API through RapidAPI.
The system integrates historical XAUUSD price information, trending market data, technical indicator calculations, automated trading signal generation, risk management, interactive visualization, and consolidated trader reporting.
The analytical workflow consists of five computational cells covering API configuration, market data extraction, technical analysis, dashboard visualization, and final trader reporting.
The technical analysis engine calculates EMA 20, EMA 50, EMA 200, RSI 14, MACD, Bollinger Bands, ATR 14, and Volume Moving Average.
The signal generation mechanism evaluates price positioning, moving average relationships, MACD conditions, and RSI momentum to classify market conditions into BUY, SELL, or WAIT.
The risk management module incorporates a USD 10,000 reference account balance, a 1% risk allocation, an ATR multiplier of 1.5, and a 1:2 risk-reward configuration.
The dashboard combines XAUUSD candlestick movements, EMA indicators, Bollinger Bands, RSI momentum, and MACD analysis into an interactive three-panel visualization.
Additionally, the framework retrieves trending market information and generates a consolidated trader report containing the latest market observations, technical indicators, trading signal, and calculated risk parameters.
Overall, the MarketFlow Trading Analyzer demonstrates how Python and financial APIs can be integrated to automate technical analysis and support structured trading decision-making.
However, the framework should be considered a rule-based trading intelligence and analytical support system rather than a validated predictive model or fully automated trading bot. The reliability of its outputs depends on API data quality, indicator initialization, signal conditions, and the accuracy of broker-specific risk calculations.
Future integration of historical backtesting, higher-timeframe confirmation, advanced position sizing, and broker execution mechanisms could further improve the analytical capabilities of the framework.

