Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

I used this code: import time from binance.client import Client from binance.enums…

  1. User

    I used this 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 = 'BTC/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 = '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… } }) time.sleep(1) 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 # Extract necessary prices from df # 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 greatest line strategy - buy signal
    if df.EMA10.iloc[-1] > df.EMA50.iloc[-1] and close_price > max(df['EMA10'].iloc[-2], df['EMA50'].iloc[-2]):
        ema_analysis.append('buy')
    
    # EMA greatest line strategy - sell signal
    elif df.EMA10.iloc[-1] < df.EMA50.iloc[-1] and close_price < min(df['EMA10'].iloc[-2], df['EMA50'].iloc[-2]):
        ema_analysis.append('sell')
    
    # Check for bullish candlestick patterns
    if open_price > close_price and previous_open < previous_close and close_price < previous_open and open_price >= previous_close:
        candle_analysis.append('sell')
    
    elif open_price < close_price and previous_open > previous_close and close_price > previous_open and open_price <= previous_close:
        candle_analysis.append('buy')
                               
        # Combine all analysis into final signal
    ema_signal = 'buy' if 'buy' in ema_analysis else 'sell' if 'sell' in ema_analysis else ''
    candle_signal = 'buy' if 'buy' in candle_analysis else 'sell' if 'sell' in candle_analysis else ''
    
    if ema_signal == 'buy' and candle_signal == 'buy':
        return 'buy'
    elif ema_signal == 'sell' and candle_signal == 'sell':
        return 'sell'
    else:
        return ''
    

    df = get_klines(symbol, '1m', 44640)

    def order_execution(symbol, signal, step_size, leverage, order_type): # Set default value for response response = {}

    # Close any existing positions
    current_position = None
    positions = binance_futures.fapiPrivateGetPositionRisk()
    for position in positions:
        if position["symbol"] == symbol:
            current_position = position
        if current_position is not None and current_position["positionAmt"] != 0:
            response = binance_futures.fapiPrivatePostOrder(
                symbol=symbol,
                side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY',
                type='MARKET',
                quantity=abs(float(current_position['positionAmt'])),
                positionSide=current_position['positionSide'],
                reduceOnly=True
            )
    
    if 'orderId' in response:
        print(f'Closed position: {response}')
    else:
        print(f'Error closing position: {response}')
    time.sleep(1)
    
    # Calculate appropriate order quantity and price based on signal
    opposite_position = None
    quantity = step_size
    position_side = None #initialise to None
    price = None
    
    # Set default take profit price
    take_profit_price = None
    stop_loss_price = None
    
    if signal == 'buy':
        position_side = 'BOTH'
        opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
        order_type = 'TAKE_PROFIT_MARKET'
        ticker = binance_futures.fetch_ticker(symbol)
        price = 0 # default price
        if 'ask' in ticker:
            price = ticker['ask']
        # perform rounding and other operations on price
        else:
        # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
            take_profit_percentage = TAKE_PROFIT_PERCENTAGE
            stop_loss_percentage = STOP_LOSS_PERCENTAGE
    
    elif signal == 'sell':
        position_side = 'BOTH'
        opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
        order_type = 'STOP_MARKET'
        ticker = binance_futures.fetch_ticker(symbol)
        price = 0 # default price
    if 'bid' in ticker:
        price = ticker['bid']
    # perform rounding and other operations on price
    else:
    # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
        take_profit_percentage = TAKE_PROFIT_PERCENTAGE
        stop_loss_percentage = STOP_LOSS_PERCENTAGE
    
    # Set stop loss price
    stop_loss_price = None
    if price is not None:
        price = round_step_size(price, step_size=step_size)
        if signal == 'buy':
            # Calculate take profit and stop loss prices for a buy signal
            take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
            stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
        elif signal == 'sell':
            # Calculate take profit and stop loss prices for a sell signal
            take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
            stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
    
    
    # Placing new order
    api_method = 'fapiPrivatePostOrder'
    params = {
        'symbol': symbol,
        'side': signal.upper(),
        'type': order_type,
        'quantity': quantity,
        'positionSide': position_side,
        'leverage': leverage,
        'price': price,
        'stopPrice': stop_loss_price,
        'takeProfit': take_profit_price
    }
    response = getattr(binance_futures, api_method)(params=params)
    if 'orderId' in response:
        print(f'Order placed: {response}')
    else:
        print(f'Error placing order: {response}')
    time.sleep(1)
    return response
    

    signal = signal_generator(df) 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 giveing me ERROR: Traceback (most recent call last): File "c:\Users\service.vscode\jew_bot.py", line 2, in from binance.client import Client File "C:\Users\service\AppData\Local\Programs\Python\Python311\Lib\site-packages\binance_init_.py", line 9, in from binance.client import Client, AsyncClient # noqa ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ImportError: cannot import name 'AsyncClient' from 'binance.client' (C:\Users\service\AppData\Local\Programs\Python\Python311\Lib\site-packages\binance\client_init_.py)

  2. Assistant

    It seems that there is an issue with importing the 'AsyncClient' module from the 'binance.client' package.

    There are a couple of possible solutions to this issue:

    1. Update the 'binance' library to the latest version: Run the following command in your terminal or command prompt to update the library:

      pip install --upgrade binance
      
    2. Check if the 'AsyncClient' module is available in a different package or import statement: Double-check the documentation or examples of the 'binance' library to see if the 'AsyncClient' module is available in a different package or statement. Update the import statement accordingly.

    3. Use a different version of the 'binance' library: If updating the library or checking for alternative import statements doesn't work, you can try using a different version of the 'binance' library that is compatible with your code. You can uninstall the current version and install a specific version using pip. For example:

      pip uninstall binance
      pip install binance==<version_number>
      

    Try one of these solutions and see if it resolves the import error.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.