Last active
August 11, 2020 03:01
-
-
Save nagishin/092785b1157d2cbe260d49b5455de339 to your computer and use it in GitHub Desktop.
bybit_get_status.ipynb
This file contains hidden or 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
{ | |
"nbformat": 4, | |
"nbformat_minor": 0, | |
"metadata": { | |
"colab": { | |
"name": "bybit_get_status.ipynb", | |
"provenance": [], | |
"collapsed_sections": [], | |
"include_colab_link": true | |
}, | |
"kernelspec": { | |
"name": "python3", | |
"display_name": "Python 3" | |
} | |
}, | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "view-in-github", | |
"colab_type": "text" | |
}, | |
"source": [ | |
"<a href=\"https://colab.research.google.com/gist/nagishin/092785b1157d2cbe260d49b5455de339/bybit_get_status.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "XFF269RVsacK", | |
"colab_type": "text" | |
}, | |
"source": [ | |
"# 必要パッケージインストール\n", | |
"まちゅけんさんのPyBybitを使用しています。<br>\n", | |
"[[note] BybitのPython自動取引用モジュール - PyBybit 2.0](https://note.com/mtkn1/n/n9ef3460e4085)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "PupwM7rTsQes", | |
"colab_type": "code", | |
"colab": {} | |
}, | |
"source": [ | |
"!pip install git+https://github.com/MtkN1/pybybit.git" | |
], | |
"execution_count": null, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "sgVHmiTlslny", | |
"colab_type": "text" | |
}, | |
"source": [ | |
"# ステータス取得関数 (get_status)\n", | |
"\n", | |
"<b>[params]</b><br>\n", | |
"* bybit_api : pybybitインスタンス (API認証済)\n", | |
"* symbol : 通貨ペア (省略時は'BTCUSD')\n", | |
"\n", | |
"<b>[return]</b><br>\n", | |
"* ステータス文字列\n", | |
"\n", | |
"<b>[note]</b><br>\n", | |
"* 関数内でRESTリクエストを3回行っています。<br>\n", | |
" APIのRateLimitおよび処理時間に制約がある場合はご注意ください。" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "UaOWOfovsohS", | |
"colab_type": "code", | |
"colab": {} | |
}, | |
"source": [ | |
"import json\n", | |
"import datetime\n", | |
"import pybybit\n", | |
"from pytz import timezone\n", | |
"\n", | |
"def get_status(bybit_api, symbol='BTCUSD'):\n", | |
" try:\n", | |
" now_time = datetime.datetime.now(timezone('Asia/Tokyo')).strftime('%Y/%m/%d %H:%M:%S')\n", | |
" msg = f'<STATUS> {symbol} {now_time}\\n'\n", | |
"\n", | |
" # 価格\n", | |
" tic = bybit_api.rest.inverse.public_tickers(symbol=symbol)\n", | |
" tic = tic.json()['result']\n", | |
" if len(tic) > 0:\n", | |
" tic = tic[0]\n", | |
" ltp = float(tic['last_price'])\n", | |
" bid = float(tic['bid_price'])\n", | |
" ask = float(tic['ask_price'])\n", | |
" mark = float(tic['mark_price'])\n", | |
" idx = float(tic['index_price'])\n", | |
" vol = int(tic['volume_24h'])\n", | |
" oi = int(tic['open_interest'])\n", | |
" fr = float(tic['funding_rate'])\n", | |
" msg += f'[price]\\n'\n", | |
" msg += f' ltp : {ltp:.1f}\\n'\n", | |
" msg += f' bid : {bid:.1f}\\n'\n", | |
" msg += f' ask : {ask:.1f}\\n'\n", | |
" msg += f' mark : {mark:.2f}\\n'\n", | |
" msg += f' index : {idx:.2f}\\n'\n", | |
" msg += f' vol_24 : {vol:,}\\n'\n", | |
" msg += f' oi : {oi:,}\\n'\n", | |
" msg += f' fr : {fr:.4%}\\n'\n", | |
"\n", | |
" # 残高&ポジション\n", | |
" pos = bybit_api.rest.inverse.private_position_list(symbol=symbol)\n", | |
" pos = pos.json()['result']\n", | |
" wlt = float(pos['wallet_balance'])\n", | |
" side = pos['side']\n", | |
" size = int(pos['size'])\n", | |
" margin = float(pos['position_margin'])\n", | |
" entry = float(pos['entry_price'])\n", | |
" sl = float(pos['stop_loss'])\n", | |
" tp = float(pos['take_profit'])\n", | |
" ts = float(pos['trailing_stop'])\n", | |
" liq = float(pos['liq_price'])\n", | |
" lvr = float(pos['effective_leverage'])\n", | |
" pnl = float(pos['unrealised_pnl'])\n", | |
" used = margin + float(pos['occ_closing_fee']) + float(pos['occ_funding_fee']) - pnl\n", | |
" avl = wlt - used\n", | |
" price_pnl = 0\n", | |
" if pos['side'] == 'Buy':\n", | |
" price_pnl = ltp - entry\n", | |
" elif pos['side'] == 'Sell':\n", | |
" price_pnl = entry - ltp\n", | |
" msg += f'[position]\\n'\n", | |
" msg += f' side : {side}\\n'\n", | |
" msg += f' size : {size:,} ({margin:.8f})\\n'\n", | |
" msg += f' avr_entry : {entry:.2f}' + f' ({price_pnl:+.2f})\\n'\n", | |
" msg += f' stop_loss : {sl:.1f}\\n'\n", | |
" msg += f' take_profit: {tp:.1f}\\n'\n", | |
" msg += f' trailing : {ts:.1f}\\n'\n", | |
" msg += f' liq_price : {liq:.1f}\\n'\n", | |
" msg += f' unrealised : {pnl:.8f}\\n'\n", | |
" msg += f' leverage : {lvr:.2f}\\n'\n", | |
" msg += f'[balance]\\n'\n", | |
" msg += f' wallet : {wlt:.8f}\\n'\n", | |
" msg += f' available : {avl:.8f}\\n'\n", | |
"\n", | |
" # オープンオーダー\n", | |
" odr = bybit_api.rest.inverse.private_order_list(symbol=symbol, order_status='New,PartiallyFilled')\n", | |
" odr = odr.json()['result']\n", | |
" if 'data' in odr and len(odr['data']) > 0:\n", | |
" msg += f'[open order]\\n'\n", | |
"\n", | |
" for o in odr['data']:\n", | |
" if o['order_status'] == 'New':\n", | |
" os = '[New ]:'\n", | |
" elif o['order_status'] == 'PartiallyFilled':\n", | |
" os = '[Partial]:'\n", | |
" else:\n", | |
" os = '[Other ]:'\n", | |
" price = float(o['price'])\n", | |
" qty = int(o['qty'])\n", | |
" cum = int(o['cum_exec_qty'])\n", | |
" msg += ' ' + os + o['order_type'] + o['side'] + f' [price]:{price:.1f} [qty]:{cum}/{qty}'\n", | |
"\n", | |
" utc_dt = datetime.datetime.strptime(o['updated_at'] + '+0000', '%Y-%m-%dT%H:%M:%S.%fZ%z')\n", | |
" jst_dt = utc_dt.astimezone(timezone('Asia/Tokyo'))\n", | |
" msg += ' [time]:' + jst_dt.strftime('%Y/%m/%d %H:%M:%S')\n", | |
"\n", | |
" opt = ''\n", | |
" if 'time_in_force' in o and len(o['time_in_force']) > 0:\n", | |
" opt += o['time_in_force']\n", | |
" if 'ext_fields' in o and 'reduce_only' in o['ext_fields'] and o['ext_fields']['reduce_only']:\n", | |
" if len(opt) > 0:\n", | |
" opt += ','\n", | |
" opt += 'ReduceOnly'\n", | |
" if len(opt) > 0:\n", | |
" msg += ' [option]:' + opt\n", | |
" msg += '\\n'\n", | |
" return msg\n", | |
"\n", | |
" except Exception as e:\n", | |
" raise Exception('get_status failed.' + str(e))\n" | |
], | |
"execution_count": 2, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"id": "MfM1mct7uqZ8", | |
"colab_type": "text" | |
}, | |
"source": [ | |
"# 使用例" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"metadata": { | |
"id": "AZkgwczcutLo", | |
"colab_type": "code", | |
"colab": { | |
"base_uri": "https://localhost:8080/", | |
"height": 476 | |
}, | |
"outputId": "5fafb7ae-5f6a-4c45-b6fa-e9d2bd1800d4" | |
}, | |
"source": [ | |
"# pybybit APIインスタンス生成\n", | |
"apis = [\n", | |
" 'your api key',\n", | |
" 'your api secret'\n", | |
"]\n", | |
"bybit_api = pybybit.API(*apis, testnet=True)\n", | |
"\n", | |
"# ステータス取得 & 出力\n", | |
"print(get_status(bybit_api))" | |
], | |
"execution_count": 3, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"text": [ | |
"<STATUS> BTCUSD 2020/08/11 12:01:10\n", | |
"[price]\n", | |
" ltp : 11872.0\n", | |
" bid : 11871.5\n", | |
" ask : 11872.0\n", | |
" mark : 11865.98\n", | |
" index : 11865.24\n", | |
" vol_24 : 470,381,991\n", | |
" oi : 21,781,128\n", | |
" fr : 0.0100%\n", | |
"[position]\n", | |
" side : Sell\n", | |
" size : 1,629 (0.00136794)\n", | |
" avr_entry : 11908.50 (+36.50)\n", | |
" stop_loss : 0.0\n", | |
" take_profit: 0.0\n", | |
" trailing : 0.0\n", | |
" liq_price : 168842.5\n", | |
" unrealised : 0.00049017\n", | |
" leverage : 1.00\n", | |
"[balance]\n", | |
" wallet : 0.13741279\n", | |
" available : 0.13652829\n", | |
"[open order]\n", | |
" [New ]:LimitSell [price]:12000.0 [qty]:0/10000 [time]:2020/08/11 09:00:54 [option]:PostOnly\n", | |
" [New ]:LimitBuy [price]:11600.0 [qty]:0/5000 [time]:2020/08/11 08:57:58 [option]:PostOnly\n", | |
"\n" | |
], | |
"name": "stdout" | |
} | |
] | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment