Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· 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 requests import json import numpy as np import pytz import datetime as dt import ccxt

    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)

    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 = 'BTC/USDT' quantity = 1 order_type = 'MARKET' leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ 'apiKey': '', 'secret': '', 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True } })

    Get server time and time difference

    def get_server_time(exchange): server_time = exchange.fetch_time() return server_time

    # Calculate time difference between server and local machine time
    

    server_time = get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time

    def get_klines(symbol, interval, lookback): url = "https://fapi.binance.com/fapi/v1/klines" start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback)) end_time = dt.datetime.now() 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('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 = get_klines('BTCUSDT', '1m', 44640) def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): # Get current account balance balances = binance_futures.fetch_balance() usdt_balance = balances['USDT']['free'] step_size = binance_futures.fapiPublicExchangeInfo({'symbol': symbol})['filters'][2]['stepSize'] max_trade_quantity = round(float(usdt_balance) * max_trade_quantity_percentage / 100 / float(step_size)) * float(step_size) max_trade_quantity = min(max_trade_quantity, 2500) # Setting a max limit of 2500 contracts to avoid high-risk trades.

    # 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["positionAmt"] != 0:
            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
            )
    time.sleep(1)
    
    # Calculate appropriate order quantity and price based on signal
    opposite_position = None
    quantity = max_trade_quantity
    if signal == 'buy':
        position_side = 'BOTH'
        opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
        order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
        price = round_step_size(binance_futures.fetch_ticker(symbol)['askPrice'], step_size=step_size)
        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 = FUTURE_ORDER_TYPE_STOP_MARKET
        price = round_step_size(binance_futures.fetch_ticker(symbol)['bidPrice'], step_size=step_size)
        take_profit_percentage = TAKE_PROFIT_PERCENTAGE
        stop_loss_percentage = STOP_LOSS_PERCENTAGE
    
    # Reduce quantity if opposite position exists
    if opposite_position is not None:
        if abs(opposite_position['positionAmt']) < quantity:
            quantity = abs(opposite_position['positionAmt'])
    
    # Set take profit and stop loss prices
    if signal == 'buy':
        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)
    else:
        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)
    
    # Place order
    order_params = {
        "symbol": symbol,
        "side": "BUY" if signal == "buy" else "SELL",
        "type": order_type,
        "positionSide": position_side,
        "quantity": quantity,
        "price": price,
        "stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
        "reduceOnly": False,
        "newOrderRespType": "RESULT",
        "workingType": "MARK_PRICE",
        "priceProtect”": False
    }
    try:
        response = binance_futures.fapiPrivatePostOrder(**order_params)
        print(f"Order details: {response}")
    except BinanceAPIException as e:
        print(f"Error in order_execution: {e}")
    

    while True: df = get_klines('BTCUSDT', '1m', 44640) if df is not None: signal = signal_generator(df) if signal: print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}") order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) df = get_klines('BTCUSDT', '1m', 44640) if df is not None: signal = signal_generator(df) if signal: print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}") order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) time.sleep(0.1) But I getting ERROR: Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 200, in order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 123, in order_execution step_size = binance_futures.fapiPublicExchangeInfo({'symbol': symbol})['filters'][2]['stepSize'] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'binance' object has no attribute 'fapiPublicExchangeInfo'

  2. Assistant

    The error is caused by using the wrong API method to get the exchange information. Replace fapiPublicExchangeInfo with load_markets to fix the issue. Here's the corrected code:

    step_size = binance_futures.load_markets()[symbol]['precision']['amount']
    

    This should retrieve the step size for the specified symbol on the Binance futures exchange.