BIBOT
BIBOT
BIBOT
전체 방문자
오늘
어제
  • 분류 전체보기 (79)
    • 경제뉴스 일기 (11)
    • 바이낸스 (17)
    • 코딩 (15)
    • 기술적 트레이딩 (27)
    • 기타 (1)
    • 경제상식 (6)
    • 일상 (1)

블로그 메뉴

  • 홈
  • 선물거래 계산기
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 파이썬 바이낸스
  • 우분투
  • 서버
  • 파이썬

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
BIBOT

BIBOT

코딩

24시간 작동하는 이동평균(Moving Average) 전략 바이낸스 선물거래 알고리즘 예시

2023. 3. 16. 00:13
pip install binance

아래 코드는 파이썬 코드는 먼저 binance 라이브러리를 설치해야 합니다.

다음은 가장 기초적인 Binance 선물거래 알고리즘 트레이딩 예제입니다. 
이 예제에서는 이동평균(Moving Average) 전략을 사용하여 롱/숏 포지션 진입 조건을 설정하고, 손절과 익절 기준을 설정합니다.
* 해당코드는 일시적으로 수익이 날 수는 있지만, 장기적으로 수익을 기다하긴 어렵습니다. 반드시 테스트용으로만 사용해주세요.

import time
import numpy as np
from binance import Client
from binance.exceptions import BinanceAPIException
from binance.enums import *

# Binance API 키 및 시크릿 키
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_SECRET_KEY'

# 파라미터 설정
symbol = 'BTCUSDT'
trade_amount = 0.001
stop_loss_percentage = 0.03  # 손절률
take_profit_percentage = 0.05  # 익절률
short_moving_average_period = 10
long_moving_average_period = 30
interval = '1m'

# 클라이언트 생성
client = Client(api_key, api_secret)

def get_moving_average(period, data):
    return np.convolve(data, np.ones(period), 'valid') / period

while True:
    try:
        # 가격 데이터 받기
        klines = client.get_historical_klines(symbol, interval, f'{long_moving_average_period} minutes ago UTC')
        close_prices = [float(kline[4]) for kline in klines]

        # 이동평균 계산
        short_ma = get_moving_average(short_moving_average_period, close_prices)[-1]
        long_ma = get_moving_average(long_moving_average_period, close_prices)[-1]

        # 포지션 정보 가져오기
        position = client.futures_position_information(symbol=symbol)[0]
        position_amount = float(position['positionAmt'])

        # 롱/숏 포지션 진입 조건 확인
        if short_ma > long_ma and position_amount <= 0:
            # 롱 포지션 진입
            order = client.futures_create_order(
                symbol=symbol,
                side=SIDE_BUY,
                type=ORDER_TYPE_MARKET,
                quantity=trade_amount,
                positionSide=POSITION_SIDE_LONG
            )

            # 익절/손절 가격 계산
            entry_price = float(order['avgPrice'])
            stop_loss_price = entry_price * (1 - stop_loss_percentage)
            take_profit_price = entry_price * (1 + take_profit_percentage)

            # 익절/손절 주문 생성
            client.futures_create_oco_order(
                symbol=symbol,
                side=SIDE_SELL,
                quantity=trade_amount,
                positionSide=POSITION_SIDE_LONG,
                stopLimitTimeInForce=TIME_IN_FORCE_GTC,
                stopLossPrice=stop_loss_price,
                stopLimitPrice=stop_loss_price,
                takeProfitPrice=take_profit_price
            )

        elif short_ma < long_ma and position_amount >= 0:
            # 숏 포지션 진입
            order = client.futures_create_order(
                symbol=symbol,
                side=SIDE_SELL,
                type=ORDER_TYPE_MARKET,
                quantity=trade_amount,
                positionSide=POSITION_SIDE_SHORT
            )

            # 익절/손절 가격 계산
            entry_price = float(order['avgPrice'])
            stop_loss_price = entry_price * (1 + stop_loss_percentage)
            take_profit_price = entry_price * (1 - take_profit_percentage)

            # 익절/손절 주문 생성
            client.futures_create_oco_order(
                symbol=symbol,
                side=SIDE_BUY,
                quantity=trade_amount,
                positionSide=POSITION_SIDE_SHORT,
                stopLimitTimeInForce=TIME_IN_FORCE_GTC,
                stopLossPrice=stop_loss_price,
                stopLimitPrice=stop_loss_price,
                takeProfitPrice=take_profit_price
            )

        # 대기 시간 설정 (예: 1분)
        time.sleep(60)

    except BinanceAPIException as e:
        print(f"Binance API 에러: {e}")
        time.sleep(60)
    except Exception as e:
        print(f"일반 에러: {e}")
        time.sleep(60)​

 

이 코드는 간단한 이동 평균 전략을 사용하여 롱 및 숏 포지션을 실행하고, 익절 및 손절 주문을 생성합니다. 주의해야 할 점은 이 예제는 테스트 목적으로만 사용되어야 하며, 실제 거래에 사용하기 전에 전략을 충분히 테스트하고 최적화해야 합니다. 또한, 사용자의 개인적인 리스크 관리 기준에 따라 손절률 및 익절률을 설정해야 합니다.

반응형
저작자표시 비영리 변경금지 (새창열림)
    '코딩' 카테고리의 다른 글
    • 파이썬으로 바이낸스 선물거래소에 있는 심볼 중 거래량과 가격 변동이 비슷한 심볼 5개를 찾는 방법
    • 바이낸스 선물 거래에서 사용할 수 있는 페어 트레이딩(Pair Trading) 전략의 예제
    • 파이썬 - 엘리어트 파동이론(Elliot Wave Theory) 마지막 파동 출력하기
    • CentosOS 7 에서 Error: rpmdb open failed의 오류가 발생한다면?
    BIBOT
    BIBOT

    티스토리툴바