ubuntu 18 버전과python 3.6 버전 pipenv 가상환경에서 진행 하였습니다.
아래 deribit 공식 git 과 api 문서 사이트를 참고 하여 만들었습니다.
https://github.com/deribit/deribit-api-python
https://docs.deribit.com/#deribit-api-v2-0-0
필요한 라이브러리
pip3 install websocket-client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import websocket | |
import json | |
import time | |
from datetime import datetime | |
def main(): | |
# 거래소에서 발급 받은 publick, secret key | |
client_id = 'key' | |
client_secret = 'secret_key' | |
def on_message(ws, message): | |
# 아래 ws.send() 에서 보낸 return message 받는 func | |
msg = json.loads(message) | |
try: | |
price = msg['params']['data']['close'] | |
# 현재 가격을 불러와 5000$ 이하일 경우 40$ 만큼 시장가로 주문 | |
if price < 5000: | |
data = { | |
"method": "/private/buy", | |
"params": { | |
"amount": 40, | |
"instrument_name": "BTC-PERPETUAL", | |
"label": "market0000234" | |
"type": "market" | |
}, | |
"jsonrpc": "2.0", | |
"id": 34 | |
} | |
ws.send(json.dumps(data)) | |
except: | |
pass | |
def on_error(ws, error): | |
print(error) | |
def on_close(ws): | |
print("### closed ###") | |
def on_open(ws): | |
data = { | |
"id" : 27, | |
"method": "public/auth", | |
"params":{ | |
"grant_type": "client_credentials", | |
"scope": "session:apiconsole-aiczudeyx0n", | |
"client_id": client_id, | |
"client_secret": client_secret, | |
}, | |
"jsonrpc": "2.0" | |
} | |
# access token 값 받기 | |
ws.send(json.dumps(data)) | |
data = { | |
"method": "/private/subscribe", | |
"params": { | |
"channels": ["chart.trades.BTC-PERPETUAL.60"], | |
} | |
} | |
# 위에서 받아온 access token 값으로 private 값 불러 오기 | |
ws.send(json.dumps(data)) | |
websocket.enableTrace(True) | |
ws = websocket.WebSocketApp("wss://www.deribit.com/ws/api/v2/", | |
on_message = on_message, | |
on_error = on_error, | |
on_close = on_close) | |
ws.on_open = on_open | |
ws.run_forever() | |
if __name__ == "__main__": | |
main() |
websocket 참고 사이트
https://pypi.org/project/websocket_client/
잘 못 되었거나 잘 모르시는 부분 있으시면 댓글 부탁 드립니다.
'개발 > Python' 카테고리의 다른 글
python plotly, dash 를 이용해서 주식 차트 (candlestick, stockchart) 만들기 (0) | 2020.06.10 |
---|---|
E: Unable to locate package python3-pip 오류 해결 (0) | 2020.05.29 |
python requests.exceptions.ConnectionError | Max retries exceeded with url 오류 (0) | 2020.03.25 |
python multiple file upload 파이썬 파일 다중 업로드 (0) | 2020.03.10 |
python 죽은 프로그램 다시 실행 시키는 os.execl 사용법 (0) | 2020.02.27 |