I used this code. This code will give me signals in termianl retirns or no ? Code:…
- User
I used this code. This code will give me signals in termianl retirns or no ? Code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date)
url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content)
API keys and other configuration
API_KEY = '' API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 0.27 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 10
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback): frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC')) frame = frame.iloc[:60,:6] frame.columns = ['Time','Open','High','Low','Close','Volume'] frame = frame.set_index('Time') today = dt.date.today() frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S") frame = frame.astype(float) return frame
def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2]
#Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' #Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' #No clear pattern else: return ''df = getminutedata('BTCUSDT', '1m', '44640') signal = ["" for i in range(len(df))] # initialize signal as a list of empty strings for i in range(1, len(df)): df_temp = df[i-1:i+1] signal[i] = signal_generator(df_temp) df["signal"] = signal
def order_execution(symbol, signal, max_trade_quantity_percentage): max_trade_quantity_percentage = 10 buy = signal == "buy" sell = signal == "sell" signal = buy or sell symbol = 'BTCUSDT'
account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 POSITION_SIDE_SHORT = SIDE_SELL POSITION_SIDE_LONG = SIDE_BUY long_position = POSITION_SIDE_LONG short_position = POSITION_SIDE_SHORT symbol = 'BTCUSDT' max_trade_quantity = 100 positions = client.futures_position_information(symbol=symbol) long_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'LONG'), None) if long_position: # Close long position if signal is opposite if signal == "sell": order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) print(f"Closed long position with order ID {order['orderId']}") time.sleep(1) else: order_quantity = min(max_trade_quantity, float(long_position) if long_position is None else 0 ) if long_position in None: print("No open long position found") order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT, leverage=leverage ) print(f"Placed short order with order ID {order['orderId']} and quantity {order_quantity})") time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order['avgPrice'] * (1 + STOP_LOSS_PERCENTAGE / 100) take_profit_price = order['avgPrice'] * (1 + TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}") time.sleep(1) short_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'SHORT'), None) if short_position: # Close short position if signal is opposite if signal == "buy": order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) print(f"Closed short position with order ID {order['orderId']}") time.sleep(1) else: order_quantity = min(max_trade_quantity, float(short_position['maxNotionalValue']) / leverage) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG, leverage=leverage ) print(f"Placed long order with order ID {order['orderId']} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order['avgPrice'] * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order['avgPrice'] * (1 - TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}") time.sleep(1)while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution(symbol, current_signal,max_trade_quantity_percentage) time.sleep(1) # Add a delay of 1 second
- Assistant
Yes, this code will print the signals in the terminal returns. It will print the current time and the current signal generated by the signal_generator function. If there is a signal, it will execute an order using the order_execution function, and print notifications about the orders placed and stop loss/take profit prices set. The code will run indefinitely in a loop, checking for signals every second.
- User
I tryed this code , but it doesn't give me any signals
- Assistant
There could be a few reasons why you're not seeing any signals:
-
Market conditions: It's possible that the current market conditions do not match the criteria for the signal_generator function to generate a buy or sell signal. The function is designed to detect specific bullish or bearish patterns in the minute data, and these patterns may not always be present.
-
Timeframe: The timeframe used in the getminutedata function (1 minute) may be too short to generate reliable signals. Consider using a longer timeframe such as 5 or 15 minutes.
-
API Keys: Make sure your API keys are correct and have the necessary permissions to execute orders.
-
Max Trade Quantity Percentage: Check that the max_trade_quantity_percentage variable is set correctly and not too low. This variable determines the maximum percentage of your account balance that can be used for a single trade.
-
Position Side: Check that the POSITION_SIDE_SHORT and POSITION_SIDE_LONG variables are set correctly, depending on your trading strategy and market conditions.
Try adjusting these variables and functions and see if you can generate any signals. Additionally, you may want to print out the values of key variables and functions to debug the code and understand why no signals are being generated.
-
- User
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date)
url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content)
API keys and other configuration
API_KEY = '' API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 0.27 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 10
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback): frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC')) frame = frame.iloc[:60,:6] frame.columns = ['Time','Open','High','Low','Close','Volume'] frame = frame.set_index('Time') today = dt.date.today() frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S") frame = frame.astype(float) return frame
def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2]
#Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' #Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' #No clear pattern else: return ''df = getminutedata('BTCUSDT', '15m', '44640') signal = ["" for i in range(len(df))] # initialize signal as a list of empty strings for i in range(1, len(df)): df_temp = df[i-1:i+1] signal[i] = signal_generator(df_temp) df["signal"] = signal
def order_execution(symbol, signal, max_trade_quantity_percentage): max_trade_quantity_percentage = 10 buy = signal == "buy" sell = signal == "sell" signal = buy or sell symbol = 'BTCUSDT'
account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 POSITION_SIDE_SHORT = SIDE_SELL POSITION_SIDE_LONG = SIDE_BUY long_position = POSITION_SIDE_LONG short_position = POSITION_SIDE_SHORT symbol = 'BTCUSDT' max_trade_quantity = 100 positions = client.futures_position_information(symbol=symbol) long_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'LONG'), None) if long_position: # Close long position if signal is opposite if signal == "sell": order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) print(f"Closed long position with order ID {order['orderId']}") time.sleep(1) else: order_quantity = min(max_trade_quantity, float(long_position) if long_position is None else 0 ) if long_position in None: print("No open long position found") order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT, leverage=leverage ) print(f"Placed short order with order ID {order['orderId']} and quantity {order_quantity})") time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order['avgPrice'] * (1 + STOP_LOSS_PERCENTAGE / 100) take_profit_price = order['avgPrice'] * (1 + TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}") time.sleep(1) short_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'SHORT'), None) if short_position: # Close short position if signal is opposite if signal == "buy": order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) print(f"Closed short position with order ID {order['orderId']}") time.sleep(1) else: order_quantity = min(max_trade_quantity, float(short_position['maxNotionalValue']) / leverage) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG, leverage=leverage ) print(f"Placed long order with order ID {order['orderId']} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order['avgPrice'] * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order['avgPrice'] * (1 - TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}") time.sleep(1)while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution(symbol, current_signal,max_trade_quantity_percentage) time.sleep(1) # Add a delay of 1 second But I getting ERROR: Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 214, in order_execution(symbol, current_signal,max_trade_quantity_percentage) File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 115, in order_execution order_quantity = min(max_trade_quantity, float(long_position) ^^^^^^^^^^^^^^^^^^^^ TypeError: float() argument must be a string or a real number, not 'NoneType'
- Assistant
The error message indicates that the
float()function is receiving a variable of a NoneType. This error is occurring because thelong_positionvariable is assigned to None when a long position does not