비트코인 (Binance) 자동매매 참고

koeyhoyh·2021년 5월 14일
3

Python

목록 보기
2/2

Binance에서 선물거래.

pip install binance-futures

pip install python-binance

참고 : https://github.com/Binance-docs/Binance_Futures_python
(https://binance-docs.github.io/apidocs/spot/en/#change-log)
참고2 : https://python-binance.readthedocs.io/en/latest/
참고3 : https://algotrading101.com/learn/binance-python-api-guide/

필수

# 나는 API와 SECRET 키를 각각
binance_api = '~~~'
binance_secret = '~~~' 
# 이렇게 지정해두었다.

request_client = RequestClient(api_key = binance_api, secret_key = binance_secret)

client = Client(binance_api, binance_secret)

현재 모든 포지션의 정보를 가져온다. (돈이나 코인이 없어도 모든 코인이 다 표기)

mode_Choice = request_client.get_position_v2();
# 정확히는, 이 정보 (헷지 모드 X)
[
    {
        "entryPrice": "0.00000",
        "marginType": "isolated", 
        "isAutoAddMargin": "false",
        "isolatedMargin": "0.00000000", 
        "leverage": "10", 
        "liquidationPrice": "0", 
        "markPrice": "6679.50671178",   
        "maxNotionalValue": "20000000", 
        "positionAmt": "0.000", 
        "symbol": "BTCUSDT", 
        "unRealizedProfit": "0.00000000", 
        "positionSide": "BOTH",
        "updateTime": 0
    }
]

# 헷지 모드
[
    {
        "entryPrice": "6563.66500", 
        "marginType": "isolated", 
        "isAutoAddMargin": "false",
        "isolatedMargin": "15517.54150468",
        "leverage": "10",
        "liquidationPrice": "5930.78",
        "markPrice": "6679.50671178",   
        "maxNotionalValue": "20000000", 
        "positionAmt": "20.000", 
        "symbol": "BTCUSDT", 
        "unRealizedProfit": "2316.83423560"
        "positionSide": "LONG", 
        "updateTime": 1625474304765
    },
    {
        "entryPrice": "0.00000",
        "marginType": "isolated", 
        "isAutoAddMargin": "false",
        "isolatedMargin": "5413.95799991", 
        "leverage": "10", 
        "liquidationPrice": "7189.95", 
        "markPrice": "6679.50671178",   
        "maxNotionalValue": "20000000", 
        "positionAmt": "-10.000", 
        "symbol": "BTCUSDT",
        "unRealizedProfit": "-1156.46711780" 
        "positionSide": "SHORT",
        "updateTime": 0
    }
]

현재 내 계좌의 정보를 가져온다. (유용하고 가져와서 사용할 수 있는 정보가 정말 많으니 참고하면 좋겠다.)

account = request_client.get_account_information()

{
    "feeTier": 0,       // account commisssion tier 
    "canTrade": true,   // if can trade
    "canDeposit": true,     // if can transfer in asset
    "canWithdraw": true,    // if can transfer out asset
    "updateTime": 0,
    "totalInitialMargin": "0.00000000",    // total initial margin required with current mark price (useless with isolated positions), only for USDT asset
    "totalMaintMargin": "0.00000000",     // total maintenance margin required, only for USDT asset
    "totalWalletBalance": "23.72469206",     // total wallet balance, only for USDT asset
    "totalUnrealizedProfit": "0.00000000",   // total unrealized profit, only for USDT asset
    "totalMarginBalance": "23.72469206",     // total margin balance, only for USDT asset
    "totalPositionInitialMargin": "0.00000000",    // initial margin required for positions with current mark price, only for USDT asset
    "totalOpenOrderInitialMargin": "0.00000000",   // initial margin required for open orders with current mark price, only for USDT asset
    "totalCrossWalletBalance": "23.72469206",      // crossed wallet balance, only for USDT asset
    "totalCrossUnPnl": "0.00000000",      // unrealized profit of crossed positions, only for USDT asset
    "availableBalance": "23.72469206",       // available balance, only for USDT asset
    "maxWithdrawAmount": "23.72469206"     // maximum amount for transfer out, only for USDT asset
    "assets": [
        {
            "asset": "USDT",            // asset name
            "walletBalance": "23.72469206",      // wallet balance
            "unrealizedProfit": "0.00000000",    // unrealized profit
            "marginBalance": "23.72469206",      // margin balance
            "maintMargin": "0.00000000",        // maintenance margin required
            "initialMargin": "0.00000000",    // total initial margin required with current mark price 
            "positionInitialMargin": "0.00000000",    //initial margin required for positions with current mark price
            "openOrderInitialMargin": "0.00000000",   // initial margin required for open orders with current mark price
            "crossWalletBalance": "23.72469206",      // crossed wallet balance
            "crossUnPnl": "0.00000000"       // unrealized profit of crossed positions
            "availableBalance": "23.72469206",       // available balance
            "maxWithdrawAmount": "23.72469206",     // maximum amount for transfer out
            "marginAvailable": true,    // whether the asset can be used as margin in Multi-Assets mode
            "updateTime": 1625474304765 // last update time 
        },
        {
            "asset": "BUSD",            // asset name
            "walletBalance": "103.12345678",      // wallet balance
            "unrealizedProfit": "0.00000000",    // unrealized profit
            "marginBalance": "103.12345678",      // margin balance
            "maintMargin": "0.00000000",        // maintenance margin required
            "initialMargin": "0.00000000",    // total initial margin required with current mark price 
            "positionInitialMargin": "0.00000000",    //initial margin required for positions with current mark price
            "openOrderInitialMargin": "0.00000000",   // initial margin required for open orders with current mark price
            "crossWalletBalance": "103.12345678",      // crossed wallet balance
            "crossUnPnl": "0.00000000"       // unrealized profit of crossed positions
            "availableBalance": "103.12345678",       // available balance
            "maxWithdrawAmount": "103.12345678",     // maximum amount for transfer out
            "marginAvailable": true,    // whether the asset can be used as margin in Multi-Assets mode
            "updateTime": 1625474304765 // last update time
        }
    ],
    "positions": [  // positions of all symbols in the market are returned
        // only "BOTH" positions will be returned with One-way mode
        // only "LONG" and "SHORT" positions will be returned with Hedge mode
        {
            "symbol": "BTCUSDT",    // symbol name
            "initialMargin": "0",   // initial margin required with current mark price 
            "maintMargin": "0",     // maintenance margin required
            "unrealizedProfit": "0.00000000",  // unrealized profit
            "positionInitialMargin": "0",      // initial margin required for positions with current mark price
            "openOrderInitialMargin": "0",     // initial margin required for open orders with current mark price
            "leverage": "100",      // current initial leverage
            "isolated": true,       // if the position is isolated
            "entryPrice": "0.00000",    // average entry price
            "maxNotional": "250000",    // maximum available notional with current leverage
            "positionSide": "BOTH",     // position side
            "positionAmt": "0",         // position amount
            "updateTime": 0           // last update time
        }
    ]
}

각 코인의 정보를 다 담고 있다.

request_client.get_symbol_price_ticker(symbol='BTCUSDT'))
{
  "symbol": "BTCUSDT",
  "price": "6000.01",
  "time": 1589437530011   // Transaction time
}

API로 거래할 때는 코인마다 정밀도(precision : 허용되는 소수점)가 존재한다.

일일이 구하던가, 혹은 찾아봐야한다.
예를 들어, DOGEUSDT는 precision이 0이라서 1개부터 살 수 있다.
그러나, BNBUSDT는 precision이 2라서 1.25개를 살 수 있다.

반드시 소숫점 자리 이상으로만 거래를 할 수 있다.

코인 정밀도는 api 에 다 나와있으니, 보고 선택하면 된다.

나는 어떻게 구하는지 몰라서 엄청나게 소규모로 실제 거래를 하면서 구해보았다... 당연히 가격에 따라 달라지겠지만 기준이 무엇인지는 잘 모르겠다.
(가상환경에서 가상의 거래를 할 수 있다고 알고 있으니 내 방법 말고, 가상환경에서 구해보는 것도 좋은 방법일 것 같다.)

참고) 정밀도(소숫점 허용자리)
ADAUSDT - 0
BNBUSDT - 2
ETCUSDT - 2
DOGEUSDT - 0
TRXUSDT - 0
LINKUSDT - 2
LTCUSDT - 3
EOSUSDT - 1
BCHUSDT - 2
DOTUSDT - 1

나는 살 코인의 양을 구하는 식이 있었기 때문에 그 식에서 구해진 코인 양에 반올림을 해 구매해주었다.


펀딩비

# 과거부터 지금까지의 펀딩비 비율을 가져온다.
# 나는 현재의 펀딩비만 필요했기 때문에 limit을 1로 정해주었다.
request_client.get_funding_rate(symbol='BTCUSDT', limit = 1)

레버리지

이 문장으로 원하는 코인의 레버리지를 변경할 수 있다.
이 문장으로 코인의 레버리지를 설정하고 거래하거나,
혹은 홈페이지에 직접 접속해 코인의 레버리지를 변경 후 거래하면 된다.

client.futures_change_leverage(symbol = 'BTCUSDT', leverage = 125)

거래

마켓 거래 (시장가 거래 : TAKER - binance 기준 수수료 0.04%)

client.futures_create_order(symbol='BTCUSDT', side='BUY',
positionSide = 'LONG', type='MARKET', quantity=0.05)

client.futures_create_order(symbol='BTCUSDT', side='SELL',
positionSide = 'SHORT', type='MARKET', quantity=0.05)

리밋 거래 (지정가 거래 : MAKER - binance 기준 수수료 0.02%)

추가된 점 :
type = 'LIMIT',
price = ??,
timeInForce = 'GTC' or 'IOC' or 'FOK' or 'GTX'

client.futures_create_order(symbol='BTCUSDT', side='BUY', positionSide = 'LONG',
type='LIMIT', price = 0.1, timeInForce = 'GTC', quantity=500)

참고 (Time In Force)

유의사항 : leverage * coin balance (레버리지 X 코인의 양)이 적어도 usdt기준 5.0(달러) 이상이어야 한다.

그 외:

LONG, BUY = 롱 포지션 오픈
SHORT, SELL = 숏 포지션 오픈
LONG, SELL = 롱 포지션 클로즈
SHORT, BUY = 숏 포지션 클로즈


존재하는 대기 주문들을 확인, 취소

존재하는 대기 주문들

# 존재하는 대기 주문들을 가져온다.
open_order = request_client.get_open_orders(symbol="TRXUSDT")

모든 대기 주문(OPEN ORDER) 취소

# countdownTime = 1ms 단위 
# 600초 뒤 TRXUSDT와 관련된 모든 대기 주문(OPEN ORDER) 취소
# result = request_client.auto_cancel_all_orders(symbol="TRXUSDT", countdownTime=600000)

Slack을 이용한 핸드폰으로 거래 알람 받기

참고 : https://www.youtube.com/channel/UCQNE2JmbasNYbjGAcuBiRRg

생각보다 정말 간단하다.

slack에 회원 가입 및 워크스페이스 생성

app 생성하기 -> bot을 입력해 실시간 메세지 봇 생성 후 token 받아오기

import requests

# slack message 보내기
def post_message(token, channel, text):
    response = requests.post("https://slack.com/api/chat.postMessage",
        headers={"Authorization": "Bearer "+token},
        data={"channel": channel,"text": text}
    )
    print(response)

myToken = '~~~"

message = (coinSet[i] + "를 거래했습니다.")
post_message(myToken, "#자신의 채널 명", message)

requests가 필요하다.

pip install requests 나
pip install --upgrade requests 로 업데이트 해주고,

이 함수를 복사 붙여넣기, 자신의 채널 명 설정해주고, 원하는 메세지를 넣어주고
원하는 곳에 집어넣기만 하면 끝이다.

유의사항 :

slack bot(app)의 token을 github 등에서 public project등으로 공개해 버릴 경우 자동으로 감지되어 비활성화된다.
당연하지만,
private repository로 설정하던가, 아예 공개를 하지 않는 것이 좋을 것이다.
물론 slack의 token 말고도 다른 api key 모두 다 말이다.


excel이나 Google Spreadsheet로 코인 판매 로그를 저장하는 방법

(작성중.)
웹 서버의 백그라운드로 돌리고 싶을 때는, excel을 이용하기 힘들 것이다. 또한 파일을 저장하는 것도 로그가 쌓여감에 있어 공간을 차지한다.

나는 Google의 google drive api나 google spreadsheet api를 추천한다.
(같은 것)


클라우드 서버 이용 방법

참고 : https://www.youtube.com/channel/UCQNE2JmbasNYbjGAcuBiRRg
조코딩님의 강의

git, github 등을 이용해 반드시 자신의 파일을 올려주어야 한다.

AWS 프리티어 서비스 무료 회원 가입

  • 컴퓨팅의 EC2 (프리 티어) 선택

-> 인스턴스

-> 인스턴스 시작

-> 우분투 서버 이용

ubuntu 기준

(*추가)한국 기준으로 서버 시간 설정: sudo ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

현재 경로 상세 출력: ls -al

경로 이동: cd 경로

vim 에디터로 파일 열기: vim ****.py

vim 에디터 입력: i

vim 에디터 저장: :wq!

패키지 목록 업데이트: sudo apt update

pip3 설치: sudo apt install python3-pip

당연하지만 pip3로 사용했던 모듈들을 다 설치해주어야 한다.

백그라운드 실행: nohup python3 bitcoinAutoTrade.py > output.log &
(nohup만 앞에 붙여줘도 상관 없다. 다만 로그가 남지 않을 뿐이다.)

실행되고 있는지 확인: ps ax | grep .py

혹은 ps ax, ps aux 등으로 PID만 확인하면 된다.

프로세스 종료(PID는 ps ax | grep .py를 했을때 확인 가능): kill -9 PID

profile
내가 만들어낸 것들로 세계에 많은 가치를 창출해내고 싶어요.

1개의 댓글

comment-user-thumbnail
2023년 7월 27일

좋은 내용 감사합니다 멋지네요! 저도 퀀트 공부하는 중인데, https://quantpro.co.kr/ 해당 사이트 퀀트 내용 어떤지 의견주시면 감사하겠습니다!

답글 달기