Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

You didn;t continue code, Code : Here’s an updated version of the code with some…

  1. User

    You didn;t continue code, Code : Here’s an updated version of the code with some improvements and suggestions:

    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 from ta import trend, momentum from ta.trend import SMAIndicator

    Helper function to format timestamps

    def format_time(timestamp): return dt.datetime.fromtimestamp(timestamp/1000).strftime(‘%Y-%m-%d %H:%M:%S’)

    Set API key and secret

    API_KEY = ‘’ API_SECRET = ‘’

    Initialize Binance Futures client

    client = Client(API_KEY, API_SECRET)

    Set endpoint and parameters for account info request

    account_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(account_url, params=params, headers={‘X-MBX-APIKEY’: API_KEY}) account_info = response.json()

    Get USDT balance and calculate max trade size based on leverage

    try: usdt_balance = next((item for item in account_info[‘accountBalance’] if item[“asset”] == “USDT”), {“free”: 0})[‘free’] except KeyError: usdt_balance = 0 print(“Error: Could not retrieve USDT balance from API response.”)

    max_trade_size = float(usdt_balance) * leverage

    Define symbol and trading parameters

    symbol = ‘BTCUSDT’ order_type = ‘MARKET’ step_size = 0.01 leverage = 100 max_trade_quantity_percentage = 1 stop_loss_percentage = -2 take_profit_percentage = 5

    Initialize Binance Futures API client

    binance_futures = ccxt.binance({ ‘apiKey’: API_KEY, ‘secret’: API_SECRET, ‘enableRateLimit’: True, ‘options’: { ‘defaultType’: ‘future’, ‘adjustForTimeDifference’: True }, ‘future’: { ‘sideEffectType’: ‘MARGIN_BUY’, } })

    Load the market symbols and check if the selected symbol is available

    markets = binance_futures.load_markets() if symbol not in markets: print(f"{symbol} not found in the market") exit()

    Define function to synchronize system clock with NTP

    def sync_time(): ntp_client = ntplib.NTPClient() response = ntp_client.request(‘pool.ntp.org’, version=3) now = time.time() offset = response.offset new_time = now + offset

    Set the system clock to the new time

    os.system(f’sudo date -s @{int(new_time)}‘) print(f’New time: {dt.datetime.now()}’)

    Define function to get klines data from Binance API

    def get_klines(symbol, interval, lookback): url = “https://fapi.binance.com/fapi/v1/klines” end_time = int(time.time() * 1000) start_time = end_time - (lookback * 60 * 1000) symbol = symbol.replace(‘/’, ‘’) 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: print(f’No data found for {symbol} klines’) return None ohlc = [] for d in data: timestamp = format_time(d[0]) 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)

  2. Assistant

    Define function to place a trade

    def place_trade(symbol, quantity, side, order_type, price=None, stop_loss=None, take_profit=None): try: if order_type == ‘MARKET’: order = binance_futures.create_order(symbol, ‘market’, side.lower(), quantity=quantity) elif order_type == ‘LIMIT’: if not price: print(‘Error: price must be specified for a limit order’) return None order = binance_futures.create_order(symbol, ‘limit’, side.lower(), quantity=quantity, price=price) if stop_loss: params = { ‘stopPrice’: round(stop_loss, step_size), ‘workingType’: ‘MARK_PRICE’, ‘quantity’: quantity, ‘reduceOnly’: True, ‘timeInForce’: ‘GTC’ } stop = binance_futures.create_order(symbol, ‘stop’, side.replace(‘BUY’, ‘SELL’).replace(‘SELL’, ‘BUY’), params=params) if take_profit: params = { ‘stopPrice’: round(take_profit, step_size), ‘workingType’: ‘MARK_PRICE’, ‘quantity’: quantity, ‘reduceOnly’: True, ‘timeInForce’: ‘GTC’ } take = binance_futures.create_order(symbol, ‘take_profit’, side, params=params) return order, stop, take except ccxt.BaseError as e: print(f’Error placing {side} {quantity} {symbol} {order_type} order: {e}’) return None

    Sync system time with NTP

    sync_time()

    Get klines data for the selected symbol and interval

    symbol_interval = ‘1h’ lookback_period = 100 klines_data = get_klines(symbol, symbol_interval, lookback_period)

    Calculate the 20- and 50-period simple moving averages (SMAs)

    sma20 = SMAIndicator(klines_data[‘Close’], 20) sma50 = SMAIndicator(klines_data[‘Close’], 50)

    Calculate the moving average convergence divergence (MACD) with default parameters

    macd = momentum.MACD(klines_data[‘Close’])

    Calculate the relative strength index (RSI) with default parameters

    rsi = momentum.RSIIndicator(klines_data[‘Close’], window=14)

    Get the current candle data

    curr_candle = klines_data.iloc[-1]

    Define trading signals based on technical indicators

    buy_signal = (sma20.iloc[-1] > sma50.iloc[-1]) and (macd.macd()[-1] > macd.signal()[-1]) and (rsi.rsi()[-1] < 30) sell_signal = (sma20.iloc[-1] < sma50.iloc[-1]) and (macd.macd()[-1] < macd.signal()[-1]) and (rsi.rsi()[-1] > 70)

    if buy_signal:

    Calculate the max trade quantity based on the available balance and max trade size

    max_trade_quantity = round(max_trade_quantity_percentage * max_trade_size / curr_candle[‘Close’], step_size)

    Place a long trade with stop loss and take profit orders

    order = place_trade(symbol, max_trade_quantity, ‘BUY’, order_type, price=curr_candle[‘Close’], stop_loss=curr_candle[‘Close’] * stop_loss_percentage / 100, take_profit=curr_candle[‘Close’] * take_profit_percentage / 100) if order: print(f’BUY order placed: {order[0][‘id’]}’) if order[1]: print(f’Stop loss order placed: {order[1][‘id’]}’) if order[2]: print(f’Take profit order placed: {order[2][‘id’]}’) elif sell_signal:

    Calculate the max trade quantity based on the available balance and max trade size

    max_trade_quantity = round(max_trade_quantity_percentage * max_trade_size / curr_candle[‘Close’], step_size)

    Place a short trade with stop loss and take profit orders

    order = place_trade(symbol, max_trade_quantity, ‘SELL’, order_type, price=curr_candle[‘Close’], stop_loss=curr_candle[‘Close’] * stop_loss_percentage / 100, take_profit=curr_candle[‘Close’] * take_profit_percentage / 100) if order: print(f’SELL order placed: {order[0][‘id’]}’) if order[1]: print(f’Stop loss order placed: {order[1][‘id’]}’) if order[2]: print(f’Take profit order placed: {order[2][‘id’]}’) else: print(‘No trading signals detected’)

    Print account balance and current position

    positions = binance_futures.fetch_positions(symbol) if positions: position_quantity = float(positions[0][‘info’][‘positionAmt’]) position_entry_price = float(positions[0][‘info’][‘entryPrice’]) position_mark_price = float(positions[0][‘info’][‘markPrice’]) position_profit_loss_ratio = round((float(positions[0][‘info’][‘unRealizedProfit’]) / float(positions[0][‘info’][‘positionInitialMargin’])) * 100, 2)

    print(f’Account balance: {usdt_balance}, Open position: {round(position_quantity, 4)} contracts @ {round(position_entry_price, 2)}, Mark Price: {round(position_mark_price, 2)}, P/L Ratio: {position_profit_loss_ratio}%’)

  3. User

    Give me right code of signal_generator , my example of code: 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)

    Define function to generate trading signals

    def signal_generator(df): indicator_window = 20 df['SMA'] = SMAIndicator(df['Close'], window=indicator_window).sma_indicator()

    buy = df['SMA'] > df['SMA'].shift(1)
    sell = df['SMA'] < df['SMA'].shift(1)
    return buy, sell
    

    df = get_klines(symbol, '1m', 44640) But it doesn't give me any live signals like buy or sell

  4. Assistant

    I see that your code defines a signal_generator function that generates trading signals based on a simple moving average indicator. However, it is not being used in the main code to generate any live buy or sell signals. Here's an updated version of the code that uses the signal_generator function to generate live signals based on the most recent candle:

    import time
    import requests
    import pandas as pd
    import ccxt
    from ta.trend import SMAIndicator
    
    # Initialize Binance Futures API client
    binance_futures = ccxt.binance({
        'apiKey': API_KEY,
        'secret': API_SECRET,
        'enableRateLimit': True,
        'options': {
            'defaultType': 'future',
            'adjustForTimeDifference': True
        },
        'future': {
            'sideEffectType': 'MARGIN_BUY',
        }
    })
    
    # Define function to get klines data from Binance API
    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 = pd.Timestamp(d[0], unit='ms', tz='UTC').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
    
    # Define function to generate trading signals
    def signal_generator(df):
        indicator_window = 20
        df['SMA'] = SMAIndicator(df['Close'], window=indicator_window).sma_indicator()
    
        buy = df['SMA'] > df['SMA'].shift(1)
        sell = df['SMA'] < df['SMA'].shift(1)
        return buy, sell
    
    # Define symbol and trading parameters
    symbol = 'BTC/USDT'
    order_type = 'MARKET'
    quantity = 0.001
    
    # Load the market symbols and check if the selected symbol is available
    markets = binance_futures.load_markets()
    if symbol not in markets:
        print(f"{symbol} not found in the market")
        exit()
    
    # Continuously check for trading signals and place orders
    while True:
        # Retrieve klines data for the selected symbol and interval
        lookback_period = 20
        klines_data = get_klines(symbol, '1m', lookback_period)
    
        # Calculate trading signals based on technical indicators
        buy_signal, sell_signal = signal_generator(klines_data)
    
        # Check if there is a buy signal and place a long trade
        if buy_signal.iloc[-1]:
            order = binance_futures.create_order(symbol, 'market', 'buy', quantity=quantity)
            print(f'BUY order placed: {order[0]["id"]}')
    
        # Check if there is a sell signal and place a short trade
        if sell_signal.iloc[-1]:
            order = binance_futures.create_order(symbol, 'market', 'sell', quantity=quantity)
            print(f'SELL order placed: {order[0]["id"]}')
    
        # Wait for a minute before checking again
        time.sleep(60)
    

    This code continuously checks for trading signals by retrieving the most recent klines data for the selected symbol and interval, generating signals based on a simple moving average indicator, and placing trades based on those signals. The code will wait for 60 seconds between each check to avoid making too many requests to the Binance API. Note that you will need to fill in your own API_KEY and API_SECRET variables to be able to place orders on Binance.

  5. User

    It giveing me : The signal time is: 2023-06-10 23:12:49:(Open time 2023-05-10 23:13:00 False 2023-05-10 23:14:00 False 2023-05-10 23:15:00 False 2023-05-10 23:16:00 False 2023-05-10 23:17:00 False ... 2023-05-11 07:28:00 False 2023-05-11 07:29:00 False 2023-05-11 07:30:00 False 2023-05-11 07:31:00 False 2023-05-11 07:32:00 False Name: SMA, Length: 500, dtype: bool, Open time 2023-05-10 23:13:00 False 2023-05-10 23:14:00 False 2023-05-10 23:15:00 False 2023-05-10 23:16:00 False 2023-05-10 23:17:00 False ... 2023-05-11 07:28:00 True 2023-05-11 07:29:00 True 2023-05-11 07:30:00 True 2023-05-11 07:31:00 Tru But it doesn't give me buy or sell signals

  6. Assistant

    It seems that the signal_generator function is correctly generating signals based on the moving average indicator, but the main code is not correctly detecting these signals.

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