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)
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)
추가된 점 :
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)
유의사항 : 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)
참고 : https://www.youtube.com/channel/UCQNE2JmbasNYbjGAcuBiRRg
생각보다 정말 간단하다.
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)
pip install requests 나
pip install --upgrade requests 로 업데이트 해주고,
이 함수를 복사 붙여넣기, 자신의 채널 명 설정해주고, 원하는 메세지를 넣어주고
원하는 곳에 집어넣기만 하면 끝이다.
유의사항 :
slack bot(app)의 token을 github 등에서 public project등으로 공개해 버릴 경우 자동으로 감지되어 비활성화된다.
당연하지만,
private repository로 설정하던가, 아예 공개를 하지 않는 것이 좋을 것이다.
물론 slack의 token 말고도 다른 api key 모두 다 말이다.
(작성중.)
웹 서버의 백그라운드로 돌리고 싶을 때는, excel을 이용하기 힘들 것이다. 또한 파일을 저장하는 것도 로그가 쌓여감에 있어 공간을 차지한다.
나는 Google의 google drive api나 google spreadsheet api를 추천한다.
(같은 것)
클라우드 서버 이용 방법
참고 : https://www.youtube.com/channel/UCQNE2JmbasNYbjGAcuBiRRg
조코딩님의 강의git, github 등을 이용해 반드시 자신의 파일을 올려주어야 한다.
AWS 프리티어 서비스 무료 회원 가입
-> 인스턴스
-> 인스턴스 시작
-> 우분투 서버 이용
(*추가)한국 기준으로 서버 시간 설정: 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
백그라운드 실행: nohup python3 bitcoinAutoTrade.py > output.log &
(nohup만 앞에 붙여줘도 상관 없다. 다만 로그가 남지 않을 뿐이다.)
실행되고 있는지 확인: ps ax | grep .py
혹은 ps ax, ps aux 등으로 PID만 확인하면 된다.
프로세스 종료(PID는 ps ax | grep .py를 했을때 확인 가능): kill -9 PID
좋은 내용 감사합니다 멋지네요! 저도 퀀트 공부하는 중인데, https://quantpro.co.kr/ 해당 사이트 퀀트 내용 어떤지 의견주시면 감사하겠습니다!