Crypto automatic purchase

24 views Asked by At

I created an automatic crypto buying and selling program, but the automatic buying and selling program works, but buying does not work.

It works well until the sale. However, if you try to print the debugging to see if the conditional expression is the problem, it does not print and you cannot buy crypto.

The crypto exchange uses Korea's Upbit, and the simple automatic buying and selling program worked well. The IDE is running with PyCharm and Anaconda.

python


import time
import pyupbit

# API
access_key = ""
secret_key = ""
upbit = pyupbit.Upbit(access_key, secret_key)

# Set which crypto to buy
target_tokens = ["KRW-BTC", "KRW-ETH", "KRW-XRP", "KRW-POLYX", "KRW-TRX", "KRW-BSV", "KRW-ID", "KRW-SOL", "KRW-STX", "KRW-CTC"]
max_buy_amount = 100000  # 각 토큰에 대해 최대 10만원씩 매수 예정
cooldown_period = 5 * 3600  # 5시간(초 단위) 동안 매수를 제한
buy_amount = 10000  # 예시로 10,000원으로 설정했습니다.

# Time setting for comparing trading volume and current price (unit: minutes)
interval = 360  # 6시간


def get_ma(ticker, days):
    df = pyupbit.get_ohlcv(ticker, interval='day', count=days)
    ma = df['close'].rolling(window=days).mean().iloc[-1]
    return ma


def get_current_price(ticker):
    return pyupbit.get_current_price(ticker)


def buy(ticker, amount):
    upbit.buy_market_order(ticker, amount)
    print(f"{ticker} 매수 완료")


def sell(ticker, amount):
    upbit.sell_market_order(ticker, amount)
    print(f"{ticker} 매도 완료")


def main():
    while True:
        try:
            # current time
            current_time = time.time()

            # 6 hours ago
            prev_time = current_time - interval * 60

            # Trading volume and current price from 6 hours ago to present
            volume_now = sum([pyupbit.get_ohlcv(target_token, interval='minute60', count=interval)['volume'].sum() for target_token in target_tokens])
            price_now = get_current_price(target_tokens)

            # Trading volume and current price from 6 hours ago to the interval time
            volume_prev = sum([pyupbit.get_ohlcv(target_token, interval='minute60', to=prev_time, count=interval)['volume'].sum() for target_token in target_tokens])
            price_prev = get_current_price(target_tokens)

            for target_token in target_tokens:
                ma5 = get_ma(target_token, 5)
                ma10 = get_ma(target_token, 10)
                ma20 = get_ma(target_token, 20)
                ma60 = get_ma(target_token, 60)
                current_price = price_now[target_token]
                prev_price = price_prev[target_token]

                # Add debugging message
                print(f"{target_token}:")
                print(f"ma5: {ma5}, ma10: {ma10}, ma20: {ma20}, ma60: {ma60}")
                print(f"current_price: {current_price}, prev_price: {prev_price}")
                print(f"volume_now: {volume_now}, volume_prev: {volume_prev}")

                # The 5-day and 10-day averages are rising, and buy when they reach a positive candle.
                if ma5 > ma10 and ma10 >= ma20 and current_price > ma5 and ma60 < ma20 and current_price > ma10 and volume_now > volume_prev and current_price < prev_price:
                    print(f"{target_token} 매수 조건 충족, 매수 실행")
                    buy(target_token, buy_amount)
                else:
                    print(f"{target_token} 매수 조건 미충족")

            time.sleep(1)  # 30분마다 실행
        except Exception as e:
            print(e)
            time.sleep(1)


def auto_trade():
    try:
        for target_token in target_tokens:
            # Check your current reserves
            balance = upbit.get_balance(target_token)
            if balance == 0:
                continue

            # Check the current average price and purchase amount
            avg_buy_price = upbit.get_avg_buy_price(target_token)
            buy_amount = avg_buy_price * balance

            # Check current price
            current_price = pyupbit.get_current_price(target_token)

            # Calculate current yield
            current_profit_rate = ((current_price - avg_buy_price) / avg_buy_price) * 100

            # Sell ​​if the rate of return is over 7%
            if current_profit_rate >= 7:
                sell(target_token, balance)
                print(f"{target_token} 매도 완료 (수익률: {current_profit_rate:.2f}%)")

            # Sell ​​if the rate of return is -5% or less.
            elif current_profit_rate <= -5:
                sell(target_token, balance)
                print(f"{target_token} 매도 완료 (수익률: {current_profit_rate:.2f}%)")

            time.sleep(1)

    except Exception as e:
        print(e)


# Execute automatic trading periodically
while True:
    auto_trade()
    time.sleep(30)  # 1분

I'm curious what part of the above code is wrong and how to fix it.

0

There are 0 answers