coincheck APIとslack APIを使ってBTCに暴落・暴騰をslackでお知らせBotを作ったった
チャート見てない時のBTC変動が知りたい!!!
最近、BTCに手を出し始めて色々とウハウハしてるのだが、運転している間や授業を受けている間もBTC価格の変 動が知りたい! と言うことでcoincheckさんが提供しているAPIとslack APIを利用して、BTCが高騰or暴落したらslackにメッセージを投げてくれるようなプログラムを作ってみた!
今回の概要
3分毎にBTCレートを取得して3分前より3000BTC以上の変動があった場合はslackに通知メッセージを投げる
各API
まぁ、本当は自動取引するスクリプト書けや、って話なんだけどそれはそれで怖いのであくまでも知らせるだけ !今回は上記URLのcoincheckのpublic APIのティッカーを使用しました!
使用した環境
- CentOS 7
- cron
- python3.6
手順
slack Web APIを使用するためtokenを取得
Slack APIを使用してメッセージを送信する Slack APIのTokenの取得・ 場所
上記の2つの記事に大変お世話になった!APIビギナーの私を助けてくれてありがとう!
上記の記事に従ってAPI tokenを取得したらコピペで保存しておくこと!
curl -XPOST -d token=取得したtoken -d channel=#random -d text=THIS_IS_TEST -d username=host https://slack.com/api/chat.postMessage
これでslackに通知ができていたら成功
coincheck APIのticker
curl GET https://coincheck.com/api/ticker
このリクエストを実行すると現在のBTCの価値などの情報がjson形式で帰ってくる
{"last":570723.0,"bid":570723.0,"ask":570817.0,"high":579499.0,"low":533102.0,"volume":43952.21153332,"timestamp":1507803511}
こいつをスクリプトの中で実行して、トリミング後にパラメータとして実行する
slackAPIへと投げてくれるスクリプトのソース
githubに全てのソースと設定ファイルを置いているので、環境さえ整っていれば動く、はず!
import subprocess
import sys
#変動幅
PRICE = 3000
FLAG = 0
#それぞれの文字列をfloat化してdiffを計算するメソッド
def calcurate(now_rate,later_rate):
now = float(now_rate)
later = float(later_rate)
result = now - later
print(result)
return result
#diffによる条件分岐メソッド
def select(result):
if result < 0 and result < -PRICE :
print("大幅下落時の処理")
#FLAG = 0
return 0
elif result > 0 and result > PRICE :
print("大幅高騰時の処理")
#FLAG = 1
return 1
elif result == 0:
print("変化なし")
else:
print("大幅な変化なし")
#slackにpost_apiを叩くメソッド
def send_slack(FLAG,now_rate,result):
if FLAG == 1:
cmd = "curl -XPOST -d token=取得したtoken -d channel=#btc_channel -d text=高騰中:Now_changing_rate_:__now_rate:" + str(now_rate) + "__:value_change:" + str(result) + " -d username=btc_alert https://slack.com/api/chat.postMessage"
subprocess.call( cmd.split(" ") )
elif FLAG == 0:
cmd = "curl -XPOST -d token=取得したtoken -d channel=#btc_channel -d text=暴落中:Now_changing_rate_:__now_rate:" + str(now_rate) + "__:value_change:" + str(result) + " -d username=btc_alert https://slack.com/api/chat.postMessage"
subprocess.call( cmd.split(" ") )
else:
print("Nothing alert")
#curlでcoincheckからパラメータ取得
cmd = "curl GET https://coincheck.com/api/ticker"
now_price = subprocess.check_output( cmd.split(" ") )
#前回スクリプト実行時のパラメータを取得
#開くファイルのパスを指定
for later_rate in open('/home/shambara/api/file.txt', 'r'):
print(later_rate)
#現在のパラメータのトリミング
print(now_price)
now_price = str(now_price)
now_price = now_price.split(",")
numresult = now_price[0].split(":")
now_rate = numresult[1]
#diff計算
result = calcurate(now_rate,later_rate)
print("result is " +str(result))
#diffにより処理分岐
FLAG = select(result)
print("FLAG is " + str(FLAG))
#slackにapiを叩く
send_slack(FLAG,now_rate,result)
#現在のパラメータを外部ファイルに保存
#書き込むファイルのパスを指定
now_rate = str(now_rate)
file = open('/home/shambara/api/file.txt','w')
file.write(now_rate)
file.close()