Convert to Python Code that Find Demand And Supply Zone on Charts on Binance using…
- User
Convert to Python Code that Find Demand And Supply Zone on Charts on Binance using public api from BTCUSDT ETHUSDT XRPUSDT DOGEUSDT SOLUSDT BNBUSDT SUIUSDT CKBUSDT FTMUSDT RUNEUSDT UNIUSDT AAVEUSDT BCHUSDT KEYUSDT 1INCHUSDT
on 30M, 1H, 2H, 4H
- Assistant
Certainly! Below is a Python script that fetches historical candlestick (kline) data from Binance's public API for the specified cryptocurrency pairs and timeframes. It then identifies potential demand and supply zones by finding swing lows and swing highs in the price data.
import requests import pandas as pd import numpy as np import time # List of cryptocurrency pairs and timeframes symbols = [ 'BTCUSDT', 'ETHUSDT', 'XRPUSDT', 'DOGEUSDT', 'SOLUSDT', 'BNBUSDT', 'SUIUSDT', 'CKBUSDT', 'FTMUSDT', 'RUNEUSDT', 'UNIUSDT', 'AAVEUSDT', 'BCHUSDT', 'KEYUSDT', '1INCHUSDT' ] timeframes = ['30m', '1h', '2h', '4h'] def get_klines(symbol, interval, limit=1000): """ Fetches historical kline data from Binance API. :param symbol: Trading pair symbol (e.g., 'BTCUSDT') :param interval: Timeframe interval (e.g., '1h') :param limit: Number of data points to retrieve (max 1000) :return: DataFrame containing kline data """ base_url = 'https://api.binance.com' endpoint = '/api/v3/klines' params = { 'symbol': symbol, 'interval': interval, 'limit': limit } response = requests.get(base_url + endpoint, params=params) data = response.json() if response.status_code != 200: print(f"Error fetching data for {symbol} at {interval}: {data}") return None 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 timestamp to datetime df['Open Time'] = pd.to_datetime(df['Open Time'], unit='ms') df['Close Time'] = pd.to_datetime(df['Close Time'], unit='ms') # Convert numeric columns to float numeric_cols = ['Open', 'High', 'Low', 'Close', 'Volume', 'Quote Asset Volume', 'Taker Buy Base Asset Volume', 'Taker Buy Quote Asset Volume'] df[numeric_cols] = df[numeric_cols].astype(float) return df def find_zones(df, N=5): """ Identifies potential demand and supply zones by finding swing lows and highs. :param df: DataFrame containing kline data :param N: Number of periods to use for swing identification :return: DataFrames containing swing highs and swing lows """ # Identify swing highs df['Swing_High'] = df['High'][ (df['High'] == df['High'].rolling(window=2*N+1, center=True).max()) & (df['High'].shift(1) != df['High']) # Exclude flat tops ] # Identify swing lows df['Swing_Low'] = df['Low'][ (df['Low'] == df['Low'].rolling(window=2*N+1, center=True).min()) & (df['Low'].shift(1) != df['Low']) # Exclude flat bottoms ] # Clean up NaN values in swings swing_highs = df.dropna(subset=['Swing_High']) swing_lows = df.dropna(subset=['Swing_Low']) return swing_highs[['Open Time', 'Swing_High']], swing_lows[['Open Time', 'Swing_Low']] def run_analysis(): """ Runs the demand and supply zone analysis for all symbols and timeframes. """ for symbol in symbols: for timeframe in timeframes: print(f"Processing {symbol} on {timeframe} timeframe...") df = get_klines(symbol, timeframe) if df is not None: swing_highs, swing_lows = find_zones(df) print(f"Found {len(swing_highs)} swing highs and {len(swing_lows)} swing lows for {symbol} on {timeframe}") # Optionally, save the results to CSV files # swing_highs.to_csv(f"{symbol}_{timeframe}_swing_highs.csv", index=False) # swing_lows.to_csv(f"{symbol}_{timeframe}_swing_lows.csv", index=False) # Pause to respect API rate limits time.sleep(0.5) # Adjust sleep time as needed else: print(f"Skipping {symbol} on {timeframe} due to API error.") print("-" * 50) if __name__ == "__main__": run_analysis()Explanation:
-
Imports:
requestsfor making HTTP requests to Binance's API.pandasfor data manipulation.numpyfor numerical operations.timefor adding delays to respect API rate limits.
-
Symbols and Timeframes:
- A list of cryptocurrency pairs and timeframes to analyze.
-
get_klinesFunction:- Fetches historical kline (candlestick) data for a given symbol and interval from Binance's public API.
- Parses the JSON response and converts it into a
pandasDataFrame. - Converts timestamp fields to human-readable datetime and numeric fields to floats.
-
find_zonesFunction:- Identifies potential demand (swing lows) and supply (swing highs) zones in the price data.
- Uses rolling windows to find local minima (swing lows) and maxima (swing highs).
- The parameter
Ndefines the number of periods on each side to consider when identifying swings.
-
run_analysisFunction:- Iterates over all symbols and timeframes.
- Fetches data and finds swing highs and lows for each combination.
- Prints the number of swings found.
- Optionally saves the results to CSV files (currently commented out).
- Adds a small delay to respect Binance API rate limits.
-
Main Execution:
- Calls the
run_analysisfunction when the script is run directly.
- Calls the
Notes:
-
API Rate Limits:
- Binance's API has rate limits. Adjust the
time.sleep()duration in therun_analysisfunction if you encounter any rate limit errors.
- Binance's API has rate limits. Adjust the
-
Swing Identification Parameters:
- The
Nparameter in thefind_zonesfunction determines how sensitive the swing detection is. - A larger
Nwill find more significant swings (major highs and lows). - Adjust
Nbased on the desired level of detail.
- The
-
Data Limitations:
- The Binance API returns a maximum of 1000 data points per request.
- For deeper historical analysis, you'll need to implement pagination using
startTimeandendTimeparameters.
-
Further Enhancements:
- Implement clustering of nearby swing highs and lows to form more precise demand and supply zones.
- Visualize the zones on charts using libraries like
matplotliborplotly. - Incorporate volume analysis to strengthen the identification of key zones.
Caution:
- Financial Disclaimer:
- This script is for educational purposes. Identifying demand and supply zones is a complex task that may require more advanced algorithms and should be validated with professional financial analysis.
Example Output:
Processing BTCUSDT on 30m timeframe... Found 11 swing highs and 12 swing lows for BTCUSDT on 30m -------------------------------------------------- Processing BTCUSDT on 1h timeframe... Found 7 swing highs and 8 swing lows for BTCUSDT on 1h -------------------------------------------------- ...This script provides a foundational approach to detecting demand and supply zones using swing highs and lows. Adjust and enhance the code based on your specific requirements and the nuances of the cryptocurrency market you're analyzing.
-