Create Python web app that find demand zone using DBR and RBR formation on binance for…
- User
Create Python web app that find demand zone using DBR and RBR formation on binance for BTCUSDT ETHUSDT XRPUSDT DOGEUSDT SOLUSDT BNBUSDT SUIUSDT CKBUSDT FTMUSDT RUNEUSDT UNIUSDT AAVEUSDT BCHUSDT KEYUSDT 1INCHUSDT using public api on 30M, 1H, 2H, 4H and Make sure these zones are not violated, still fresh
- Assistant
Sure! I can help you create a Python web application that identifies demand zones using Drop-Base-Rally (DBR) and Rally-Base-Rally (RBR) formations on Binance for the specified cryptocurrency pairs and timeframes. We'll use Binance's public API to fetch historical data and analyze it to find the desired patterns.
Here's an outline of what we'll cover:
- Setup the Environment
- Connect to Binance API and Fetch Data
- Implement Logic to Identify DBR and RBR Formations
- Check for Fresh (Unviolated) Demand Zones
- Create a Web Application to Display Results
Let's go through each step in detail.
1. Setup the Environment
Install Required Libraries
We'll use the following Python libraries:
requestsfor API callspandasfor data manipulationFlaskfor the web application framework
Install them using pip:
pip install requests pandas flask
2. Connect to Binance API and Fetch Data
Function to Fetch Historical Kline Data
We'll use Binance's REST API endpoint
/api/v3/klinesto fetch candlestick data.import requests import pandas as pd def get_klines(symbol, interval, limit=500): url = 'https://api.binance.com/api/v3/klines' params = { 'symbol': symbol, 'interval': interval, 'limit': limit # Adjust as needed (max 1000 for Binance) } response = requests.get(url, params=params) data = response.json() # Convert data to DataFrame df = pd.DataFrame(data, columns=[ 'Open Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close Time', 'Quote Asset Volume', 'Number of Trades', 'Taker Buy Base Volume', 'Taker Buy Quote Volume', 'Ignore' ]) # Convert data types numeric_columns = ['Open', 'High', 'Low', 'Close', 'Volume'] df[numeric_columns] = df[numeric_columns].astype(float) df['Open Time'] = pd.to_datetime(df['Open Time'], unit='ms') df['Close Time'] = pd.to_datetime(df['Close Time'], unit='ms') return df
3. Implement Logic to Identify DBR and RBR Formations
Understanding DBR and RBR Patterns
- Drop-Base-Rally (DBR): Price drops, forms a base (consolidation), then rallies.
- Rally-Base-Rally (RBR): Price rallies, forms a base, then rallies again.
Implement Pattern Detection Functions
We'll define functions to detect these patterns based on candlestick data.
def find_dbr(df): patterns = [] for i in range(2, len(df) - 3): # Identify a drop (price decrease) if df['Close'][i - 2] < df['Close'][i - 3] and df['Close'][i - 1] < df['Close'][i - 2]: # Identify base (small movement) base_range = df['High'][i] - df['Low'][i] prev_range = (df['High'][i - 1] - df['Low'][i - 1] + df['High'][i - 2] - df['Low'][i - 2]) / 2 if base_range < prev_range * 0.5: # Identify rally (price increase) if df['Close'][i + 1] > df['Close'][i] and df['Close'][i + 2] > df['Close'][i + 1]: pattern = { 'Type': 'DBR', 'Index': i, 'Base Start': df['Open Time'][i], 'Base End': df['Close Time'][i], 'Demand Zone High': df['High'][i], 'Demand Zone Low': df['Low'][i], } patterns.append(pattern) return patterns def find_rbr(df): patterns = [] for i in range(2, len(df) - 3): # Identify a rally (price increase) if df['Close'][i - 2] > df['Close'][i - 3] and df['Close'][i - 1] > df['Close'][i - 2]: # Identify base (small movement) base_range = df['High'][i] - df['Low'][i] prev_range = (df['High'][i - 1] - df['Low'][i - 1] + df['High'][i - 2] - df['Low'][i - 2]) / 2 if base_range < prev_range * 0.5: # Identify rally continuation if df['Close'][i + 1] > df['Close'][i] and df['Close'][i + 2] > df['Close'][i + 1]: pattern = { 'Type': 'RBR', 'Index': i, 'Base Start': df['Open Time'][i], 'Base End': df['Close Time'][i], 'Demand Zone High': df['High'][i], 'Demand Zone Low': df['Low'][i], } patterns.append(pattern) return patternsNote: The logic above is simplified and may require adjustments to match precise definitions of DBR and RBR formations.
4. Check for Fresh (Unviolated) Demand Zones
Function to Determine if a Zone is Fresh
A demand zone is considered fresh if the price hasn't returned to that zone since its formation.
def is_zone_fresh(df, index, demand_zone_high, demand_zone_low): # Check subsequent candles to see if the price has entered the demand zone for i in range(index + 1, len(df)): if df['Low'][i] <= demand_zone_high and df['High'][i] >= demand_zone_low: # Price has re-entered the demand zone return False return True
5. Create a Web Application to Display Results
Initialize the Flask App
from flask import Flask, render_template app = Flask(__name__)Define the Routing Logic
@app.route('/') def index(): symbols = [ 'BTCUSDT', 'ETHUSDT', 'XRPUSDT', 'DOGEUSDT', 'SOLUSDT', 'BNBUSDT', 'SUIUSDT', 'CKBUSDT', 'FTMUSDT', 'RUNEUSDT', 'UNIUSDT', 'AAVEUSDT', 'BCHUSDT', 'KEYUSDT', '1INCHUSDT' ] intervals = ['30m', '1h', '2h', '4h'] all_patterns = [] for symbol in symbols: for interval in intervals: df = get_klines(symbol, interval) dbr_patterns = find_dbr(df) rbr_patterns = find_rbr(df) patterns = dbr_patterns + rbr_patterns # Check for fresh zones fresh_patterns = [] for pattern in patterns: if is_zone_fresh(df, pattern['Index'], pattern['Demand Zone High'], pattern['Demand Zone Low']): pattern['Symbol'] = symbol pattern['Interval'] = interval fresh_patterns.append(pattern) all_patterns.extend(fresh_patterns) return render_template('index.html', patterns=all_patterns)Create the HTML Template
Create a folder named
templatesin the same directory as your Python script. Insidetemplates, create anindex.htmlfile.<!-- templates/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Demand Zones Finder</title> </head> <body> <h1>Fresh Demand Zones</h1> <table border="1"> <thead> <tr> <th>Symbol</th> <th>Interval</th> <th>Type</th> <th>Base Start</th> <th>Base End</th> <th>Demand Zone High</th> <th>Demand Zone Low</th> </tr> </thead> <tbody> {% for pattern in patterns %} <tr> <td>{{ pattern.Symbol }}</td> <td>{{ pattern.Interval }}</td> <td>{{ pattern.Type }}</td> <td>{{ pattern['Base Start'] }}</td> <td>{{ pattern['Base End'] }}</td> <td>{{ pattern['Demand Zone High'] }}</td> <td>{{ pattern['Demand Zone Low'] }}</td> </tr> {% endfor %} </tbody> </table> </body> </html>Run the Flask Application
if __name__ == '__main__': app.run(debug=True)
Complete Code (app.py)
Here's the complete code combining all the steps:
import requests import pandas as pd from flask import Flask, render_template app = Flask(__name__) def get_klines(symbol, interval, limit=500): url = 'https://api.binance.com/api/v3/klines' params = {'symbol': symbol, 'interval': interval, 'limit': limit} response = requests.get(url, params=params) data = response.json() df = pd.DataFrame(data, columns=[ 'Open Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close Time', 'Quote Asset Volume', 'Number of Trades', 'Taker Buy Base Volume', 'Taker Buy Quote Volume', 'Ignore' ]) numeric_columns = ['Open', 'High', 'Low', 'Close', 'Volume'] df[numeric_columns] = df[numeric_columns].astype(float) df['Open Time'] = pd.to_datetime(df['Open Time'], unit='ms') df['Close Time'] = pd.to_datetime(df['Close Time'], unit='ms') return df def find_dbr(df): patterns = [] for i in range(2, len(df) - 3): if df['Close'][i - 2] < df['Close'][i - 3] and df['Close'][i - 1] < df['Close'][i - 2]: base_range = df['High'][i] - df['Low'][i] prev_range = (df['High'][i - 1] - df['Low'][i - 1] + df['High'][i - 2] - df['Low'][i - 2]) / 2 if base_range < prev_range * 0.5: if df['Close'][i + 1] > df['Close'][i] and df['Close'][i + 2] > df['Close'][i + 1]: pattern = { 'Type': 'DBR', 'Index': i, 'Base Start': df['Open Time'][i], 'Base End': df['Close Time'][i], 'Demand Zone High': df['High'][i], 'Demand Zone Low': df['Low'][i], } patterns.append(pattern) return patterns def find_rbr(df): patterns = [] for i in range(2, len(df) - 3): if df['Close'][i - 2] > df['Close'][i - 3] and df['Close'][i - 1] > df['Close'][i - 2]: base_range = df['High'][i] - df['Low'][i] prev_range = (df['High'][i - 1] - df['Low'][i - 1] + df['High'][i - 2] - df['Low'][i - 2]) / 2 if base_range < prev_range * 0.5: if df['Close'][i + 1] > df['Close'][i] and df['Close'][i + 2] > df['Close'][i + 1]: pattern = { 'Type': 'RBR', 'Index': i, 'Base Start': df['Open Time'][i], 'Base End': df['Close Time'][i], 'Demand Zone High': df['High'][i], 'Demand Zone Low': df['Low'][i], } patterns.append(pattern) return patterns def is_zone_fresh(df, index, demand_zone_high, demand_zone_low): for i in range(index + 1, len(df)): if df['Low'][i] <= demand_zone_high and df['High'][i] >= demand_zone_low: return False return True @app.route('/') def index(): symbols = [ 'BTCUSDT', 'ETHUSDT', 'XRPUSDT', 'DOGEUSDT', 'SOLUSDT', 'BNBUSDT', 'SUIUSDT', 'CKBUSDT', 'FTMUSDT', 'RUNEUSDT', 'UNIUSDT', 'AAVEUSDT', 'BCHUSDT', 'KEYUSDT', '1INCHUSDT' ] intervals = ['30m', '1h', '2h', '4h'] all_patterns = [] for symbol in symbols: for interval in intervals: df = get_klines(symbol, interval) dbr_patterns = find_dbr(df) rbr_patterns = find_rbr(df) patterns = dbr_patterns + rbr_patterns fresh_patterns = [] for pattern in patterns: if is_zone_fresh(df, pattern['Index'], pattern['Demand Zone High'], pattern['Demand Zone Low']): pattern['Symbol'] = symbol pattern['Interval'] = interval fresh_patterns.append(pattern) all_patterns.extend(fresh_patterns) return render_template('index.html', patterns=all_patterns) if __name__ == '__main__': app.run(debug=True)
Run the Application
-
Save the code in a file named
app.py. -
Ensure the
templatesfolder contains theindex.htmlfile as shown. -
Run the application:
python app.py -
Open your web browser and navigate to
http://localhost:5000.
Considerations
-
Accuracy: The pattern detection logic is a simplified version. You might need to refine the criteria to improve accuracy based on how strictly you want to define DBR and RBR patterns.
-
Performance: Fetching data for multiple symbols and intervals can be time-consuming. Consider implementing caching mechanisms or optimizing API calls.
-
Rate Limits: Binance API has rate limits. Ensure your application respects these limits to avoid getting blocked.
-
Error Handling: The code lacks robust error handling for brevity. In a production environment, you should add try-except blocks and handle potential exceptions gracefully.
-
Security: Since we are using public data, security concerns are minimal. However, always be cautious when dealing with APIs and user input.
Feel free to ask if you have any questions or need further assistance modifying the code to suit your specific requirements!