Creating a Python web application that identifies demand zones on candlestick charts using DBR (Drop-Base-Rally) and RBR (Rally-Base-Rally) formations requires integrating several components:
- Data Retrieval: Fetching historical price data from the Binance public API.
- Pattern Recognition: Implementing algorithms to detect DBR and RBR formations.
- Visualization: Drawing candlestick charts and overlaying the demand zones.
- Web Framework: Setting up a web application to display the charts.
Below is a step-by-step guide to help you build this application.
Prerequisites
- Python 3.x
- Libraries:
requests: For API calls.
pandas: Data manipulation.
numpy: Numerical computations.
matplotlib or plotly: Charting library.
ta-lib or TA-Lib wrapper: Technical analysis (optional).
Flask or Django: Web framework.
- Binance API Key: Not required for public data.
1. Set Up the Web Application Framework
We'll use Flask for simplicity.
pip install flask requests pandas numpy matplotlib
Create a file app.py:
from flask import Flask, render_template, request
import requests
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import io
import base64
app = Flask(__name__)
2. Fetch Historical Price Data from Binance
Binance provides a RESTful API for public data.
Endpoint: https://api.binance.com/api/v3/klines
Function to Fetch Data:
def fetch_klines(symbol, interval, limit=500):
url = "https://api.binance.com/api/v3/klines"
params = {
'symbol': symbol,
'interval': interval,
'limit': limit # Max 1000
}
response = requests.get(url, params=params)
data = response.json()
# Create a DataFrame
df = pd.DataFrame(data, columns=[
'Open time', 'Open', 'High', 'Low', 'Close', 'Volume',
'Close time', 'Quote asset volume', 'Number of trades',
'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore'
])
# Convert to appropriate data types
df['Open time'] = pd.to_datetime(df['Open time'], unit='ms')
df['Close time'] = pd.to_datetime(df['Close time'], unit='ms')
numeric_cols = ['Open', 'High', 'Low', 'Close', 'Volume']
df[numeric_cols] = df[numeric_cols].astype(float)
return df
3. Implement Pattern Recognition for DBR and RBR Formations
Understanding DBR and RBR Formations:
- DBR (Drop-Base-Rally): Price drops, forms a base (consolidation), then rallies.
- RBR (Rally-Base-Rally): Price rallies, forms a base, then continues rallying.
Algorithm to Identify Bases:
-
Identify Bases:
- A base can be identified by a series of small-bodied candles with low volatility.
- Alternatively, use Average True Range (ATR) to find periods of consolidation.
-
Detecting DBR and RBR Patterns:
- DBR: Look for a significant bearish candle(s), a base, then a significant bullish candle(s).
- RBR: Look for a bullish trend, a base, then continuation of the bullish trend.
Example Function to Detect DBR (Simplified):
def detect_dbr(df):
demand_zones = []
for i in range(2, len(df)-2):
# Check for Drop
if df['Close'][i-2] < df['Close'][i-3] and df['Close'][i-1] < df['Close'][i-2]:
# Check for Base
base_condition = (abs(df['Close'][i] - df['Open'][i]) / (df['High'][i] - df['Low'][i]) < 0.3)
# Check for Rally
if df['Close'][i+1] > df['Close'][i] and df['Close'][i+2] > df['Close'][i+1]:
if base_condition:
zone = {
'start': df['Open time'][i],
'end': df['Open time'][i+1],
'low': df['Low'][i],
'high': df['High'][i]
}
demand_zones.append(zone)
return demand_zones
Note: This is a simplified version. In practice, you would need a more robust method.
4. Ensure Zones Are Fresh and Not Violated
- Fresh Zone: A demand zone that price has not revisited since its formation.
- Not Violated: The price has not moved below the demand zone after its formation.
Check if Zone Is Still Fresh:
def is_zone_fresh(df, zone_index):
zone_low = df['Low'][zone_index]
zone_high = df['High'][zone_index]
# Check subsequent candles
for i in range(zone_index+1, len(df)):
if df['Low'][i] <= zone_low:
# Zone is violated
return False
elif df['High'][i] >= zone_high:
# Price has moved away from the zone
return True
return True
5. Plot Candlestick Chart and Demand Zones
Using Matplotlib:
import matplotlib.dates as mdates
from mpl_finance import candlestick_ohlc
def plot_chart(df, demand_zones):
df['Date'] = mdates.date2num(df['Open time'])
ohlc = df[['Date', 'Open', 'High', 'Low', 'Close']]
fig, ax = plt.subplots(figsize=(12,6))
# Plot candlestick chart
candlestick_ohlc(ax, ohlc.values, width=0.0005, colorup='g', colordown='r')
# Plot demand zones
for zone in demand_zones:
zone_start = mdates.date2num(zone['start'])
zone_end = mdates.date2num(zone['end'])
rect = plt.Rectangle(
(zone_start, zone['low']),
zone_end - zone_start,
zone['high'] - zone['low'],
linewidth=1,
edgecolor='blue',
facecolor='blue',
alpha=0.3
)
ax.add_patch(rect)
# Format the x-axis with dates
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
plt.xticks(rotation=45)
plt.tight_layout()
# Save the plot to a BytesIO object
img = io.BytesIO()
plt.savefig(img, format='png')
img.seek(0)
# Encode the image to display it on the web page
plot_url = base64.b64encode(img.getvalue()).decode('utf8')
return plot_url
6. Integrate Everything into Flask Routes
Create Routes in app.py:
@app.route('/')
def index():
return render_template('index.html')
@app.route('/chart', methods=['POST'])
def chart():
symbol = request.form['symbol']
interval = request.form['interval']
df = fetch_klines(symbol, interval)
demand_zones = detect_dbr(df)
fresh_zones = [zone for zone in demand_zones if is_zone_fresh(df, df[df['Open time'] == zone['start']].index[0])]
plot_url = plot_chart(df, fresh_zones)
return render_template('chart.html', plot_url=plot_url)
7. Create HTML Templates
templates/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Demand Zone Finder</title>
</head>
<body>
<h1>Select Symbol and Interval</h1>
<form action="/chart" method="post">
<label for="symbol">Symbol:</label>
<select name="symbol">
<option value="BTCUSDT">BTCUSDT</option>
<option value="ETHUSDT">ETHUSDT</option>
<!-- Add other symbols -->
</select><br>
<label for="interval">Interval:</label>
<select name="interval">
<option value="30m">30 Minutes</option>
<option value="1h">1 Hour</option>
<option value="2h">2 Hours</option>
<option value="4h">4 Hours</option>
</select><br>
<input type="submit" value="Get Chart">
</form>
</body>
</html>
templates/chart.html:
<!DOCTYPE html>
<html>
<head>
<title>Demand Zone Chart</title>
</head>
<body>
<h1>Demand Zone Chart</h1>
<img src="data:image/png;base64, {{ plot_url }}" alt="Chart">
<br>
<a href="/">Back</a>
</body>
</html>
8. Run the Flask Application
At the end of your app.py:
if __name__ == '__main__':
app.run(debug=True)
Run the application:
python app.py
Navigate to http://127.0.0.1:5000/ in your web browser.
9. Additional Considerations
- Customization: Adjust the pattern detection algorithm to better suit your needs.
- Error Handling: Add try-except blocks and check for API call failures.
- Optimization: For large datasets and multiple users, consider optimizing data fetching and processing.
- Deployment: When deploying to a production server, disable
debug mode and consider using a WSGI server like Gunicorn.
- Security: Ensure that the web application is secure, especially if you plan to expose it publicly.
10. Additional Enhancements
- Multiple Timeframes: Allow users to select multiple timeframes and display them simultaneously.
- Technical Indicators: Integrate other technical indicators for better analysis.
- Interactivity: Use
plotly for interactive charts.
- Caching: Implement caching mechanisms to reduce API calls and improve performance.
Example with Plotly for Interactive Charts
Install Plotly:
pip install plotly
Modify the Plot Function:
import plotly.graph_objects as go
def plot_chart(df, demand_zones):
fig = go.Figure(data=[go.Candlestick(
x=df['Open time'],
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close']
)])
# Add demand zones as shapes
for zone in demand_zones:
fig.add_shape(
type="rect",
x0=zone['start'],
y0=zone['low'],
x1=zone['end'],
y1=zone['high'],
fillcolor="LightSeaGreen",
opacity=0.5,
layer="below",
line_width=0,
)
fig.update_layout(xaxis_rangeslider_visible=False)
# Convert the plotly figure to JSON
graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
return graphJSON
Update the Template to Render the Plotly Chart:
In chart.html:
<!DOCTYPE html>
<html>
<head>
<title>Demand Zone Chart</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<h1>Demand Zone Chart</h1>
<div id="chart"></div>
<script>
var graph = {{ plot_url | safe }};
Plotly.newPlot('chart', graph.data, graph.layout);
</script>
<br>
<a href="/">Back</a>
</body>
</html>
Conclusion
This guide provides a foundation for building a Python web application that identifies and displays demand zones using DBR and RBR formations based on Binance's public API data. You can extend and customize the application to include more features, better pattern detection algorithms, and improved user interface elements.
Disclaimer: Trading involves financial risk. The provided application is for educational purposes and should not be used as a sole resource for making trading decisions.