def buyTrade(interval=[]): try: if not api.getchildorders(product_code="BTC_JPY")[0]['child_order_state'] == "ACTIVE": # お財布状況(リファクタリング候補) Amount = buyOrderAmount() buyOrder(Amount["buyPrice"],Amount["buySize"]) # print('買い注文:', buyOrderResult["buyPrice"],'/', buyOrderResult["buySize"] ) # comment='買い注文:', Amount["buyPrice"],'/', Amount["buySize"] comment='○買い注文' lineNotify.main(comment) sleep(shortsleep) while not api.getchildorders(product_code="BTC_JPY")[0]['child_order_state'] == "COMPLETED": if api.getchildorders(product_code="BTC_JPY")[0]['child_order_state'] == "ACTIVE": # お財布状況(リファクタリング候補) api.cancelallchildorders(product_code="BTC_JPY") sleep(1) Amount = buyOrderAmount() if Amount["buySize"] < 0.0001: break buyOrder(Amount["buyPrice"],Amount["buySize"]) # comment='買い注文訂正:', Amount["buyPrice"],'/',Amount["buySize"] # lineNotify.main(comment) sleep(shortsleep) elif api.getchildorders(product_code="BTC_JPY")[0]['child_order_state'] == "REJECTED": comment='注文失敗!注文やめまーす!どんまい' lineNotify.main(comment) sleep(shortsleep) break elif api.getchildorders(product_code="BTC_JPY")[0]['child_order_state'] == "CANCELED": sleep(shortsleep) break # 約定通知 getexecutions = api.getexecutions(product_code="BTC_JPY")[0] try: exectime = dt.strptime(getexecutions['exec_date'], '%Y-%m-%dT%H:%M:%S.%f') except: exectime = dt.strptime(getexecutions['exec_date'], '%Y-%m-%dT%H:%M:%S') if exectime.minute == datetime.datetime.now().minute: # comment='買い注文約定:', getexecutions['price'],'/', getexecutions['size'] comment= '○買い注文約定',getexecutions['price'] lineNotify.main(comment) sleep(interval) else: getexecutions = api.getexecutions(product_code="BTC_JPY")[1] # comment='買い注文約定?:', getexecutions['price'],'/', getexecutions['size'] comment='○買い注文約定?',getexecutions['price'] lineNotify.main(comment) sleep(interval) except: comment='Please check buy trade system' lineNotify.main(comment)
conn.commit() # 買いシグナルが発生した場合 if oneMinuteDataAll[0][0] == 1: # アクティブな注文の有無を確認 getchildorders = api.getchildorders(product_code="BTC_JPY", child_order_state="ACTIVE") if getchildorders == []: #active order is nothing # お財布状況(リファクタリング候補) buyOrderResult = buyOrderAmount() # print('買い注文:', buyOrderResult["buyPrice"],'/', buyOrderResult["buySize"] ) comment = '買い注文:', buyOrderResult[ "buyPrice"], '/', buyOrderResult["buySize"] lineNotify.main(comment) sleep(shortsleep) while api.getchildorders(product_code="BTC_JPY" )[0]['child_order_state'] == "ACTIVE": getchildorders = api.getchildorders( product_code="BTC_JPY")[0] if getchildorders['side'] == 'BUY': # お財布状況(リファクタリング候補) cancelallchildorders = api.cancelallchildorders( product_code="BTC_JPY") sleep(1) buyOrderResult = buyOrderAmount() comment = '買い注文訂正:', buyOrderResult[ "buyPrice"], '/', buyOrderResult["buySize"]
def main(): # APIへアクセス api = pybitflyer.API( ) # 取得するデータを選択する # option = ['timestamp','ltp'] # best_ask:最高買価格 # best_bid:最低売価格 # best_ask_size:最高買価格数 # best_bid_size:最低売価格数 # ltp:最終取引価格 # total_ask_depth:買注文総数 # total_bid_depth:売注文総数 # volume_by_product: 価格ごとの出来高 # 取得間隔(秒) # interval = 10 # API_KEY = setting.API_KEY # API_SECRET = setting.API_SECRET RDShost = setting.RDShost RDSpass = setting.RDSpass RDSdb = setting.RDSdb RDSuser = setting.RDSuser # coding:utf-8 # コネクションの作成 conn = mydb.connect( host =RDShost, port ='3306', user =RDSuser, password=RDSpass, database=RDSdb, charset="utf8" ) # カーソルを取得する cur = conn.cursor() try: # 取得 ticker = api.ticker(product_code="BTC_JPY") # 保存用にコンマ区切りにする # line = ','.join([str(ticker[op]) for op in option]) # レコード追加のSQL文 add_bttable =("INSERT INTO got_data " "(timestamp, price) " "VALUES (%s, %s)" ) try: btdate = dt.strptime(ticker['timestamp'], '%Y-%m-%dT%H:%M:%S.%f') except: btdate = dt.strptime(ticker['timestamp'], '%Y-%m-%dT%H:%M:%S') # パラメータの設定 btdata = ( btdate, ticker['ltp'] ) # SQL文の実行 cur.execute(add_bttable, btdata) conn.commit() # 指定した秒数だけストップ # sleep(interval) # comment="データ取得システムにエラーが発生したよ!" # lineNotify.main(comment) # sleep(interval) except: comment="データ取得システムにエラーが発生したよ!20秒止めて様子みるよ!" lineNotify.main(comment) sleep(20)
def main(): # 取得間隔(秒) # interval = 60 # API_KEY = setting.API_KEY # API_SECRET = setting.API_SECRET RDShost = setting.RDShost RDSpass = setting.RDSpass RDSdb = setting.RDSdb RDSuser = setting.RDSuser # coding:utf-8 # コネクションの作成 conn = mydb.connect( host =RDShost, port ='3306', user =RDSuser, password=RDSpass, database=RDSdb, charset="utf8" ) # カーソルを取得する cur = conn.cursor() try: cur.execute("SELECT * FROM got_data ORDER BY id DESC LIMIT 6;") rows = cur.fetchall() data = [] for i in rows: data.append(i[-1]) # 最大値 maxinum = max(data) # 最小値 minimam = min(data) # 始値 open = rows[-1][-1] # print(start) # 終値 close = rows[0][-1] # print(end) # データ作成時間(1minデータの最新時間とする) timestamp = rows[0][1] ## MACDを作成 # 手前に新しいデータの順でSQLから取得 cur.execute("SELECT * FROM 1min_table ORDER BY id DESC LIMIT 26;") oneMinuteDataAll = cur.fetchall() oneMinuteDataPrice = [] for i in oneMinuteDataAll: oneMinuteDataPrice.append(i[5]) # 手前が古い順に並び直す oneMinuteDataPriceR = list(reversed(oneMinuteDataPrice)) # 短期EMA def shortEma(oneMinuteDataPriceR=[], term = 12): s = pd.Series(oneMinuteDataPriceR) sma = s.rolling(term).mean()[:term] return list(pd.concat([sma, s[term:]]).ewm(span=term, adjust=False).mean()) shortEma=shortEma(oneMinuteDataPriceR)[-1] if math.isnan(shortEma): shortEma = "0" # 一番後ろのデータが最新のEMAになる # 長期EMA def longEma(oneMinuteDataPriceR=[], term = 26): s = pd.Series(oneMinuteDataPriceR) sma = s.rolling(term).mean()[:term] return list(pd.concat([sma, s[term:]]).ewm(span=term, adjust=False).mean()) longEma = longEma(oneMinuteDataPriceR)[-1] if math.isnan(longEma): longEma = "0" # MACD # MACD = [x - y for (x, y) in zip(shortEma, longEma)] try: MACD = shortEma - longEma except: MACD = "0" # MACDSignal oneMinuteDataMACD = [] for i in oneMinuteDataAll: oneMinuteDataMACD.append(i[-2]) oneMinuteDataMACDR = list(reversed(oneMinuteDataMACD)) def MACDSignal(oneMinuteDataMACDR=[], term = 9): s = pd.Series(oneMinuteDataMACDR) sma = s.rolling(term).mean()[:term] return list(pd.concat([sma, s[term:]]).ewm(span=term, adjust=False).mean()) MACDSignal = MACDSignal(oneMinuteDataMACDR)[-1] if math.isnan(MACDSignal): MACDSignal = "0" # BUYSig = False # SELLSig = False # BuySignal # 前回のデータがMACD<MACDSignal try: if oneMinuteDataAll[0][-2] < oneMinuteDataAll[0][-1]: # かつ今回のデータがMACD>MACDSignal if MACD > MACDSignal: BUYSig = True else: BUYSig = False else: BUYSig = False except: BUYSig = False print("buySigError") # SellSignal # 前回のデータがMACD>MACDSignal try: if oneMinuteDataAll[0][-2] > oneMinuteDataAll[0][-1]: # かつ今回のデータがMACD<MACDSignal if MACD < MACDSignal: SELLSig = True else: SELLSig = False else: SELLSig = False except: SELLSig = False print("sellSigError") add_bttable =("INSERT INTO 1min_table " "(timestamp, BUYSig, SELLSig, open, close, max, min, shortEma, longEma, MACD, MACDSignal)" "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" ) btdata = ( timestamp, BUYSig, SELLSig, open, close, maxinum, minimam, shortEma, longEma, MACD, MACDSignal ) # SQL文の実行 cur.execute(add_bttable, btdata) conn.commit() # print(btdata) except: comment="データ取得システムにエラーが発生したよ!" lineNotify.main(comment)