I used your code: import time from binance.client import Client from binance.enums…
- User
I used your 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 API_KEY = '' API_SECRET = ''
client = Client(API_KEY, API_SECRET)
Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account" timestamp = int(time.time() * 1000) recv_window = 5000
params = { "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 leverage = 100
Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY}) account_info = response.json()
Get the USDT balance and calculate the max trade size based on the leverage
usdt_balance = next((item for item in account_info['assets'] if item["asset"] == "USDT"), {"balance": 0}) max_trade_size = float(usdt_balance.get("balance", 0)) * leverage
Get the current time and timestamp
now = dt.datetime.now() date = now.strftime("%m/%d/%Y %H:%M:%S") print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' quantity = 1 symbol = 'BTC/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… } })
Load the market symbols
try: markets = binance_futures.load_markets() except ccxt.BaseError as e: print(f'Error fetching markets: {e}') markets = []
if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market")
Get server time and time difference
def get_server_time(exchange): server_time = exchange.fetch_currencies() return server_time['timestamp']
def get_time_difference(): server_time = get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time return time_difference time.sleep(1)
def get_klines(symbol, interval, lookback): url = "" 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' } try: 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 except requests.exceptions.RequestException as e: print(f'Error in get_klines: {e}') return None df = get_klines(symbol, '1m', 44640)
- Assistant
It looks like the issue is with the
binance_futures.fapiPrivatePostOrder()method call in theorder_execution()function. The error says that the method is receiving an unexpected keyword argument 'data'. According to the Binance API documentation, thefapiPrivatePostOrder()method does not have a 'data' parameter.You might want to try removing the 'data' parameter from the method call and check if it resolves the issue. The updated method call would look like:
response = binance_futures.fapiPrivatePostOrder( symbol=symbol, sideEffectType='MARGIN_BUY', type='MARKET' if signal == 'buy' else 'STOP_MARKET', quantity=quantity, positionSide=POSITION_SIDE_LONG if signal == 'buy' else POSITION_SIDE_SHORT, reduceOnly=True, newOrderRespType='FULL', stopPrice=stop_loss_price, price=price, workingType='MARK_PRICE', priceProtect=False, timeInForce='GTC', newClientOrderId='' )Make sure to remove the 'data=data' parameter from the method call.
- User
I getting ERROR: The signal time is: 2023-06-08 22:25:01, signal:sell Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 292, in order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type) File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 248, in order_execution response = binance_futures.fapiPrivatePostOrder( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Entry.init..unbound_method() got an unexpected keyword argument 'symbol'. And when I getting buy signal long position doesn't executing
- Assistant
The error message indicates that the
binance_futures.fapiPrivatePostOrder()method is receiving an unexpected keyword argument 'symbol'. This is likely because thefapiPrivatePostOrder()method for Binance futures does not have a 'symbol' parameter.To fix this, you can remove the 'symbol' keyword argument from the
binance_futures.fapiPrivatePostOrder()method call. Instead, you can pass the symbol as part of the 'data' parameter.Here's an example updated
binance_futures.fapiPrivatePostOrder()method call:response = binance_futures.fapiPrivatePostOrder( data={ 'symbol': 'BTCUSDT', 'side': 'SELL' if current_position['positionSide'] == 'LONG' else 'BUY', 'type': 'MARKET', 'quantity': abs(float(current_position['positionAmt'])), 'positionSide': current_position['positionSide'], 'reduceOnly': True } )Replace 'BTCUSDT' with your desired symbol.
Regarding the long position not executing when you receive a buy signal, it's possible that there is an issue with your signal generation logic or order execution logic. You can try adding print statements or logs to see what steps are being executed and whether there are any errors that are occurring.
- User
Give me just right code of order_execution
- Assistant