I used your signal_generator code: import time from binance.client import Client from…
- User
I used your signal_generator code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException from binance.helpers import round_step_size import pandas as pd import json import numpy as np import pytz import datetime as dt import ccxt from decimal import Decimal import requests import hmac import hashlib import ntplib import os import ta import ta.volatility API_KEY = '' API_SECRET = ''
client = Client(API_KEY, API_SECRET)
def sync_time(): server_time = requests.get('https://api.binance.com/api/v3/time').json()['serverTime'] local_time = int(time.time() * 1000) time_difference = server_time - local_time # Set the system clock to the new time os.system(f'sudo date -s @{int(server_time/1000)}') print(f'New time: {dt.datetime.now()}')
Sync your local time with the server time
sync_time()
Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v1/klines" symbol = 'COMP/USDT' interval = '1m' lookback = 44640 timestamp = int(time.time() * 1000) - 500 # subtract 500ms from local time to account for clock-drift recv_window = 60000 # increased recv_window value params = { "symbol": symbol.replace("/", ""), "interval": interval, "startTime": int((time.time() - lookback * 60) * 1000), "endTime": int(time.time() * 1000), "timestamp": timestamp, "recvWindow": recv_window }
Sign the message using the Client’s secret key
message = "&".join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params[signature] = signature
Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
Check for errors in the response
response.raise_for_status()
STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' quantity = 1 symbol = 'COMP/USDT' order_type = 'market' leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True },'future': { 'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc… } }) time.sleep(1) print(symbol) def get_klines(symbol, interval, lookback): url = "https://fapi.binance.com/fapi/v1/klines" end_time = int(time.time() * 1000) # end time is now start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago symbol = symbol.replace("/", "") # remove slash from symbol query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } response = requests.get(url + query_params, headers=headers) response.raise_for_status() data = response.json() if not data: # if data is empty, return None print('No data found for the given timeframe and symbol') return None ohlc = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S') ohlc.append({ 'Open time': timestamp, 'Open': float(d[1]), 'High': float(d[2]), 'Low': float(d[3]), 'Close': float(d[4]), 'Volume': float(d[5]) }) df = pd.DataFrame(ohlc) df.set_index('Open time', inplace=True) return df df = get_klines(symbol, '1m', 44640)
def signal_generator(df): # Calculate EMA and MA lines df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean() df['EMA10'] = df['Close'].ewm(span=10, adjust=False).mean() df['EMA20'] = df['Close'].ewm(span=20, adjust=False).mean() df['EMA50'] = df['Close'].ewm(span=50, adjust=False).mean() df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean() df['EMA200'] = df['Close'].ewm(span=200, adjust=False).mean() df['MA10'] = df['Close'].rolling(window=10).mean() df['MA20'] = df['Close'].rolling(window=20).mean() df['MA50'] = df['Close'].rolling(window=50).mean() df['MA100'] = df['Close'].rolling(window=100).mean() # Extract necessary prices from df open_price = df.Open.iloc[-1] close_price = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2]
# Calculate the last candlestick last_candle = df.iloc[-1] current_price = df.Close.iloc[-1] # Initialize analysis variables ema_analysis = [] candle_analysis = [] # EMA strategy - buy signal if df['EMA5'].iloc[-1] > df['EMA10'].iloc[-1] > df['EMA20'].iloc[-1] > df['EMA50'].iloc[-1]: ema_analysis.append('buy') # EMA strategy - sell signal elif df['EMA5'].iloc[-1] < df['EMA10'].iloc[-1] < df['EMA20'].iloc[-1] < df['EMA50'].iloc[-1]: ema_analysis.append('sell') # Check for bullish candlestick pattern - buy signal open_price = df['Open'].iloc[-1] close_price = df['Close'].iloc[-1] previous_open = df['Open'].iloc[-2] previous_close = df['Close'].iloc[-2] if ( open_price < close_price and previous_open > previous_close and close_price > previous_open and open_price <= previous_close ): candle_analysis.append('buy') # Check for bearish candlestick pattern - sell signal elif ( open_price > close_price and previous_open < previous_close and close_price < previous_open and open_price >= previous_close ): candle_analysis.append('sell') # Determine final signal if 'buy' in ema_analysis and 'buy' in candle_analysis and df['Close'].iloc[-1] > df['EMA50'].iloc[-1]: final_signal = 'buy' elif 'sell' in ema_analysis and 'sell' in candle_analysis and df['Close'].iloc[-1] < df['EMA50'].iloc[-1]: final_signal = 'sell' else: final_signal = '' return final_signaldf = get_klines(symbol, '1m', 44640)
while True: df = get_klines(symbol, '1m', 44640) # await the coroutine function here if df is not None: signal = signal_generator(df) if signal is not None: print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:{signal}") time.sleep(1) But it gave me wrong signal , plase can you give me more good code which will give me right signals , and please can you add in my EMA analysis EMA 100 and EMA 200 lines please
- Assistant
Certainly! Here is an updated version of your code with the additional EMA lines (100 and 200) added to the EMA analysis in the signal_generator function:
import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException from binance.helpers import round_step_size import pandas as pd import json import numpy as np import pytz import datetime as dt import ccxt from decimal import Decimal import requests import hmac import hashlib import ntplib import os import ta import ta.volatility API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) def sync_time(): server_time = requests.get('https://api.binance.com/api/v3/time').json()['serverTime'] local_time = int(time.time() * 1000) time_difference = server_time - local_time # Set the system clock to the new time os.system(f'sudo date -s @{int(server_time/1000)}') print(f'New time: {dt.datetime.now()}') # Sync your local time with the server time sync_time() # Set the endpoint and parameters for the request url = "https://fapi.binance.com/fapi/v1/klines" symbol = 'COMP/USDT' interval = '1m' lookback = 44640 timestamp = int(time.time() * 1000) - 500 # subtract 500ms from local time to account for clock-drift recv_window = 60000 # increased recv_window value params = { "symbol": symbol.replace("/", ""), "interval": interval, "startTime": int((time.time() - lookback * 60) * 1000), "endTime": int(time.time() * 1000), "timestamp": timestamp, "recvWindow": recv_window } # Sign the message using the Client’s secret key message = "&".join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params[signature] = signature # Send the request using the requests library response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY}) # Check for errors in the response response.raise_for_status() STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' quantity = 1 symbol = 'COMP/USDT' order_type = 'market' leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True },'future': { 'sideEffectType': 'MARGIN_BUY', } }) time.sleep(1) print(symbol) def get_klines(symbol, interval, lookback): url = "https://fapi.binance.com/fapi/v1/klines" end_time = int(time.time() * 1000) start_time = end_time - (lookback * 60 * 1000) symbol = symbol.replace("/", "") query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } response = requests.get(url + query_params, headers=headers) response.raise_for_status() data = response.json() if not data: print('No data found for the given timeframe and symbol') return None ohlc = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S') ohlc.append({ 'Open time': timestamp, 'Open': float(d[1]), 'High': float(d[2]), 'Low': float(d[3]), 'Close': float(d[4]), 'Volume': float(d[5]) }) df = pd.DataFrame(ohlc) df.set_index('Open time', inplace=True) return df df = get_klines(symbol, '1m', 44640) def signal_generator(df): df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean() df['EMA10'] = df['Close'].ewm(span=10, adjust=False).mean() df['EMA20'] = df['Close'].ewm(span=20, adjust=False).mean() df['EMA50'] = df['Close'].ewm(span=50, adjust=False).mean() df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean() df['EMA200'] = df['Close'].ewm(span=200, adjust=False).mean() df['MA10'] = df['Close'].rolling(window=10).mean() df['MA20'] = df['Close'].rolling(window=20).mean() df['MA50'] = df['Close'].rolling(window=50).mean() df['MA100'] = df['Close'].rolling(window=100).mean() open_price = df.Open.iloc[-1] close_price = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] last_candle = df.iloc[-1] current_price = df.Close.iloc[-1] ema_analysis = [] candle_analysis = [] if df['EMA5'].iloc[-1] > df['EMA10'].iloc[-1] > df['EMA20'].iloc[-1] > df['EMA50'].iloc[-1] > df['EMA100'].iloc[-1] > df['EMA200'].iloc[-1]: ema_analysis.append('buy') elif df['EMA5'].iloc[-1] < df['EMA10'].iloc[-1] < df['EMA20'].iloc[-1] < df['EMA50'].iloc[-1] < df['EMA100'].iloc[-1] < df['EMA200'].iloc[-1]: ema_analysis.append('sell') if ( open_price < close_price and previous_open > previous_close and close_price > previous_open and open_price <= previous_close ): candle_analysis.append('buy') elif ( open_price > close_price and previous_open < previous_close and close_price < previous_open and open_price >= previous_close ): candle_analysis.append('sell') if 'buy' in ema_analysis and 'buy' in candle_analysis and df['Close'].iloc[-1] > df['EMA200'].iloc[-1]: final_signal = 'buy' elif 'sell' in ema_analysis and 'sell' in candle_analysis and df['Close'].iloc[-1] < df['EMA200'].iloc[-1]: final_signal = 'sell' else: final_signal = '' return final_signal df = get_klines(symbol, '1m', 44640) while True: df = get_klines(symbol, '1m', 44640) if df is not None: signal = signal_generator(df) if signal is not None: print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:{signal}") time.sleep(1)This code should give you more accurate signals by considering the EMA lines 100 and 200 in the analysis.
- User
I tryed your code , but it gave me loss , listean me please I have stop loss -10% I need to code which position whcih position will doesn't touch this stop loss
- Assistant
To prevent your position from touching the stop loss at -10%, you can modify the
signal_generator()function to include a check for the current position and adjust the signal accordingly. Here's an updated version of the code that incorporates this logic:import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException from binance.helpers import round_step_size import pandas as pd import json import numpy as np import pytz import datetime as dt import ccxt from decimal import Decimal import requests import hmac import hashlib import ntplib import os import ta import ta.volatility API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) def sync_time(): server_time = requests.get('https://api.binance.com/api/v3/time').json()['serverTime'] local_time = int(time.time() * 1000) time_difference = server_time - local_time # Set the system clock to the new time os.system(f'sudo date -s @{int(server_time/1000)}') print(f'New time: {dt.datetime.now()}') # Sync your local time with the server time sync_time() # Set the endpoint and parameters for the request url = "https://fapi.binance.com/fapi/v1/klines" symbol = 'COMP/USDT' interval = '1m' lookback = 44640 timestamp = int(time.time() * 1000) - 500 # subtract 500ms from local time to account for clock-drift recv_window = 60000 # increased recv_window value params = { "symbol": symbol.replace("/", ""), "interval": interval, "startTime": int((time.time() - lookback * 60) * 1000), "endTime": int(time.time() * 1000), "timestamp": timestamp, "recvWindow": recv_window } # Sign the message using the Client’s secret key message = "&".join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params[signature] = signature # Send the request using the requests library response