soominkim Study
article thumbnail
728x90

 

TradingView 설정을 모두 마쳤다면 이제는 Python을 통해 Flask를 설정할 차례입니다.

바이낸스에서 제공하는 SDK를 활용해도 되지만 저는 이전의 암호화폐서비스를 하면서 해둔 것들이 있기때문에 SDK를 활용하지 않았습니다.  필요한 기능들은 선물거래 계정에 대한 잔액조회, 포지션조회, 포지션에 대한 각 옵션 설정, 실시간 가격정도 있습니다.

 

1. 계정조회

def initData(apiKey, secKey):
    headers = {
    'X-MBX-APIKEY':apiKey,
    }
    now = requests.get('https://api.binance.com/api/v3/time').json()['serverTime']
    message = f'timestamp={now}'
    signature = hmac.new(key=secKey.encode('utf-8'), msg=message.encode('utf-8'),
                         digestmod=hashlib.sha256).hexdigest()
    URL = f'{base_url}/fapi/v2/account?{message}&signature={signature}'
    response = requests.get(URL,headers=headers)
    return response.json()

계정 조회를 할 때 balance 엔드포인트를 타도되지만, 저는 기본적으로 교차(CROSS)로 매매를 진행할 예정이므로 계정(accout) 엔드포인트로 진행했습니다.

 

2. 거래타입

def marginType(apiKey, secKey, symbol):
    '''
    =================================================================================================================
    ISOLATED
    CROSSED
    =================================================================================================================
    '''
    headers = {
    'X-MBX-APIKEY':apiKey,
    }
    now = requests.get('https://api.binance.com/api/v3/time').json()['serverTime'] 
    message = f'symbol={symbol}&marginType=CROSSED&timestamp={now}'
    signature = hmac.new(key=secKey.encode('utf-8'), msg=message.encode('utf-8'),
                         digestmod=hashlib.sha256).hexdigest()
    URL = f'{base_url}/fapi/v1/marginType?{message}&signature={signature}'
    response = requests.post(URL,headers=headers)

    return response.json()

위에서 언급했던 것 처럼 기본적으로 교차(CROSS)매매이기 때문에 옵션값을 고정해두었고, 추후 웹에서 옵션 선택에 따라 변경할 예정입니다. 

 

3. 배율설정

def setLeverage(apiKey, secKey, symbol, leverage):
    headers = {
    'X-MBX-APIKEY':apiKey,
    }
    now = requests.get('https://api.binance.com/api/v3/time').json()['serverTime'] 
    message = f'symbol={symbol}&leverage={leverage}&timestamp={now}'
    signature = hmac.new(key=secKey.encode('utf-8'), msg=message.encode('utf-8'),
                         digestmod=hashlib.sha256).hexdigest()
    URL = f'{base_url}/fapi/v1/leverage?{message}&signature={signature}'
    response = requests.post(URL,headers=headers)

    return response.json()

웹에서 요청한 배율에 따라 배율이 변경되며 저는 기본적으로 5배율을 사용하고 있습니다. 전략에 따른 적절한 배율을 설정하는 것을 권장합니다.

 

4. 주문

def order(apiKey, secKey, symbol, positionSide, side, price, quantity):
    headers = {
    'X-MBX-APIKEY':apiKey,
    }
    now = requests.get('https://api.binance.com/api/v3/time').json()['serverTime'] 
    message = f'symbol={symbol}&positionSide={positionSide}&side={side}&type=LIMIT&price={price}&quantity={quantity}&timestamp={now}&timeInForce=GTC'
    signature = hmac.new(key=secKey.encode('utf-8'), msg=message.encode('utf-8'),
                         digestmod=hashlib.sha256).hexdigest()
    URL = f'{base_url}/fapi/v1/order?{message}&signature={signature}'
    response = requests.post(URL,headers=headers)

    return response.json()

단일모드가 아닌 교차모드이며, 기본적으로 지정가로만 매수/매도를 진행합니다. 단일모드에 대한 것은 파라미터의 값이 변경되기 때문에 바이낸스API 공식문서를 참조하십시오.

 

5. 포지션조회

def holdPosition(ping, API_KEY, SECRET_KEY):
    headers = {
    'X-MBX-APIKEY':API_KEY,
    }
    now = requests.get('https://api.binance.com/api/v3/time').json()['serverTime']
    message = f'timestamp={now}'
    signature = hmac.new(key=SECRET_KEY.encode('utf-8'), msg=message.encode('utf-8'),
                         digestmod=hashlib.sha256).hexdigest()
    URL = f'{base_url}{ping}?{message}&signature={signature}'
    response = requests.get(URL,headers=headers)
    return response.json()

현재 가지고있는 포지션을 조회합니다.

 

설정한 URL의 Flask에 웹훅 요청이 들어오게되면 다음 사진처럼 어떤 코인인지, 어떤 요청인지, 가격은 얼마인지 보여지게 됩니다. 그리고 실제로 매매가 이루어지게됩니다.

잠깐의 여담으로 전략에 따른 매매도 매매지만, TradingView에서 보여주는 전략테스터 결과(백테스팅)은 과거 데이터를 기반으로 한 결과입니다. 그리고 실제 매매에서는 다른 결과를 도출할 수 있습니다. 그래서 저는 해당 전략에 따른 롱/숏 비율과 승/패를 수집하고 있는데 바이낸스 자체 페이지를 이용할 경우 Position History를 제공해 손쉽게 포지션의 매매에 대한 상세내역을 볼 수 있지만, API로는 제공하지 않고 있어 승/패 수집에 어려움이 있습니다. 거래가 한번에 성사되면 상관이 없지만 해당 거래에 대해 여러번 나눠 걸쳐지는 경우, 해당 거래가 몇 번을 했는지 어디까지가 해당 거래인지 명확하게 구분이 안되는 것이 있었습니다. (방법 아시면 공유부탁드립니다.)

 

다시 본론으로 돌아와서, 위 처럼 설정하게되면 API를 통해 원하는 것을 가져오는 것은 마무리가 되며 이제 상세한 설정은

필요에 따라 코드를 작성하여 활용할 수 있습니다.

 

본 글은 웹프로젝트의 기록물입니다.

This article is a record of the web project.

 

728x90
profile

soominkim Study

@soominkim

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그