I used this code: import time from binance.client import Client from binance.enums…
- 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 = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback): klines = client.get_historical_trades(symbol, interval, str(lookback)+'min ago UTC') # Cast tuples to lists ohlc = [] for i in klines: ohlc.append([i[0], float(i[1]), float(i[2]), float(i[3]), float(i[4]), float(i[5]), i[6], float(i[7]), float(i[8]), float(i[9]), float(i[10]), float(i[11]), float(i[12])]) frame = pd.DataFrame(ohlc, 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', 'Take profit']) frame = frame[['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched return frame print(getminutedata('BTCUSDT','1m',44640))
df = getminutedata('BTCUSDT', '1m', 44640) 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) def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): signal = signal_generator(df) max_trade_quantity = None 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
# Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p['positionSide'] == 'LONG': long_position = p elif p['positionSide'] == 'SHORT': short_position = p if long_position is not None and short_position is not None: print("Multiple positions found. Closing both positions.") if long_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) if short_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) time.sleep(1) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") return order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position is not None and opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True, positionSide=opposite_position['positionSide'] ) time.sleep(1) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, # add position side parameter leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") return order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") return order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) # Print order creation confirmation messages print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1) - Assistant
The error is occurring in the
getminutedatafunction when callingclient.get_historical_trades(symbol, interval, str(lookback)+'min ago UTC'). This method expects only 2 arguments, but you are passing 4.To fix this, you need to change the method being called from
client.get_historical_tradestoclient.futures_historical_klinesand update the arguments being passed accordingly.Replace the following lines in your code:
klines = client.get_historical_trades(symbol, interval, str(lookback)+'min ago UTC') # Cast tuples to lists ohlc = [] for i in klines: ohlc.append([i[0], float(i[1]), float(i[2]), float(i[3]), float(i[4]), float(i[5]), i[6], float(i[7]), float(i[8]), float(i[9]), float(i[10]), float(i[11]), float(i[12])]) frame = pd.DataFrame(ohlc, 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', 'Take profit']) frame = frame[['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']] - User
It need to seem like that ? Code: def getminutedata(symbol, interval, lookback): klines = client.get_historical_trades(symbol, interval, str(lookback)+'min ago UTC') # Cast tuples to lists ohlc = [] for i in klines: ohlc.append([i[0], float(i[1]), float(i[2]), float(i[3]), float(i[4]), float(i[5]), i[6], float(i[7]), float(i[8]), float(i[9]), float(i[10]), float(i[11]), float(i[12])]) frame = pd.DataFrame(ohlc, 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', 'Take profit']) frame = frame[['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched return frame
- Assistant
Yes, that's correct. The
getminutedatafunction should now look like:def getminutedata(symbol, interval, lookback): klines = client.futures_historical_klines(symbol, interval, str(lookback)+' min ago UTC') ohlc = [] for i in klines: ohlc.append([i[0], float(i[1]), float(i[2]), float(i[3]), float(i[4]), float(i[5])]) frame = pd.DataFrame(ohlc, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']) frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) return frameThis code uses
client.futures_historical_klinesmethod to get historical klines data and creates a DataFrame with the OHLCV data. It also converts theOpen timecolumn todatetimeand sets it as the index of the DataFrame. Finally, it drops the last candle because it might not be fully formed yet, and returns the DataFrame. - User
But
client.futures_historical_klinesis doesn't working - Assistant
If
client.futures_historical_klinesis not working for you, there could be several reasons why. Here are a few things you could try:-
Make sure that you have the latest version of the
binancelibrary installed. You can do this by runningpip install --upgrade binance. -
Check if you are using the correct endpoint. Futures data is available on a separate endpoint (), so make sure that you are using this endpoint to call instead of .
-
- User
But is client.futures_account_balance() is undefind
- Assistant
If
client.futures_account_balance()is undefined, there could be several reasons why. Here are a few things you could try:-
Make sure that you have the latest version of the
binancelibrary installed. You can do this by runningpip install --upgrade binance. -
Check if you are using the correct endpoint. Futures data is available on a separate endpoint (
https://fapi.binance.com), so make sure that you are using this endpoint to callclient = Client(API_KEY, API_SECRET, tld='com')instead ofclient = Client(API_KEY, API_SECRET). -
Check if your API key and secret are correct and have the necessary permissions to access account balance data. You can verify this by checking if you can access other API endpoints like .
-
- User
How full code need to seem ?
- Assistant
Here's how your updated code could look like with the changes I suggested:
import time import pandas as pd import requests import json import pytz import datetime as dt from binance.client import Client from binance.enums import * date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S