def get_predict(): regr = get_model() select_feat = [ 'open', 'high', 'low', 'close', 'vol', 'amount', 'count', 'oc', 'lh' ] curkline = HuobiService.get_kline('btcusdt', '1min', 1) curdata = dict() #print(int(curkline['ts'])) curdata['time'] = (curkline['ts']) / 1000 #print(curdata['ts']) curdata['close'] = curkline['data'][0]['close'] testdata = pd.DataFrame(curkline['data']) testdata['oc'] = (testdata['open'] - testdata['close']) testdata['lh'] = (testdata['high'] - testdata['low']) testdata = testdata[select_feat] # train_data = xgb.DMatrix(train_data) # print(train_data) y_pred_xgb = regr.predict(testdata) y_pred = np.exp(y_pred_xgb) pred_time = get_nextmin(int(curkline['ts']) / 1000) predict_data = dict() predict_data['time'] = pred_time predict_data['close'] = int(y_pred[0]) #print(predict_data) return jsonify({'curdata': curdata, 'pred_data': predict_data})
def get_model(): kline_data = HuobiService.get_kline('btcusdt', '1min', 2000) kline_data = kline_data['data'] train_df = pd.DataFrame(kline_data) train_df['oc'] = (train_df['open'] - train_df['close']) train_df['lh'] = (train_df['high'] - train_df['low']) label = train_df[:-1]['close'] train_df = train_df[1:] train_df = train_df.reset_index(drop=True) train_df['label'] = label select_feat = [ 'open', 'high', 'low', 'close', 'vol', 'amount', 'count', 'oc', 'lh' ] label_df = pd.DataFrame(index=train_df.index, columns=["label"]) label_df["label"] = np.log(train_df["label"]) train_df = train_df[select_feat] def rmse(y_true, y_pred): return np.sqrt(mean_squared_error(y_true, y_pred)) regr = xgb.XGBRegressor(colsample_bytree=0.5, gamma=0.0, learning_rate=0.01, max_depth=6, min_child_weight=1.5, n_estimators=2200, reg_alpha=0.9, reg_lambda=0.6, subsample=0.8, seed=2018, silent=1) regr.fit(train_df, label_df) return regr
def addSymbol(needAdd): logUtil.info("needAdd={}".format(needAdd)) for model in needAdd: logUtil.info("begin add={}".format(model)) kline = huobi.get_kline(model.symbol, model.period, 1000) datas = kline['data'] datas.reverse() for data in datas: commonUtil.addSymbol(data, model, False) logUtil.info("end add={}".format(model))
def get_data_to_local(self, path, size=120): res = HuobiService.get_kline( self._symbol, self.period_type(self._kline_series._period_type), size) print res kline_file = '%s/huobi_kline_%s.json' % (path, date_tools.cur_time()) fout = open(kline_file, 'w') fout.write(json.dumps(res)) res = HuobiService.get_depth(self._symbol, 'step0') print res depth_file = '%s/huobi_deep_%s.json' % (path, date_tools.cur_time()) fout = open(depth_file, 'w') fout.write(json.dumps(res))
def getKline(): symbol = request.args.get("symbol", default="btcusdt") period = request.args.get("period", default="1min") size = request.args.get("size", type=int, default=300) ret = {} data_pre = HuobiService.get_kline(symbol, period, size) kline = [] for item in data_pre["data"]: temp = [] time = ts_to_time(item['id']) temp.append(time) temp.append(item['open']) temp.append(item['close']) temp.append(item['low']) temp.append(item['high']) kline.append(temp) ret['data'] = kline return jsonify(ret)
def doCheck(self, transactionModels): for transactionModel in transactionModels: symbol = transactionModel.symbol sellOrderModels = modelUtil.getSellOrderModels(symbol, self.env) if len(sellOrderModels) > 0: for sellOrderModel in sellOrderModels: orderStatus = self.chechOrder(sellOrderModel.sellOrderId) logUtil.info("orderId=", sellOrderModel.sellOrderId, " status=", orderStatus) if orderStatus: buyModel = modelUtil.getBuyModelByOrderId( sellOrderModel.buyOrderId) modelUtil.delBuyModel(buyModel.id) modelUtil.delSellOrderById(sellOrderModel.id) modelUtil.insertBuySellReocrd( buyModel.symbol, 0, sellOrderModel.buyPrice, sellOrderModel.sellPrice, sellOrderModel.buyOrderId, sellOrderModel.sellOrderId, sellOrderModel.amount, int(time.time())) continue # 测试环境不会走到这里,因为测试环境能直接卖成功 kline = huobi.get_kline(symbol, transactionModel.period, 1) if kline['status'] == 'ok' and kline['data'] and len( kline['data']) >= 1: kline['data'].reverse() price = float(kline['data'][0]['close']) buyPrice = float(sellOrderModel.buyPrice) if buyPrice > price: # 当前价格比买入的时候低才需要判断要不要撤单 gap = (buyPrice - price) / buyPrice if gap > 0.05: # 比买入的时候还要低5%就撤单 #{'status': 'ok', 'data': '82495000363'} result = huobi.cancel_order( sellOrderModel.sellOrderId) if result['status'] == 'ok': modelUtil.delSellOrderById( sellOrderModel.id) buyModel = modelUtil.getBuyModelByOrderId( sellOrderModel.buyOrderId) buyModel.status = 0 modelUtil.modBuyModel(buyModel)
symbols = huobi.get_symbols() datas = symbols['data'] symbolsList = [] for data in datas: quote_currency = data['quote-currency'] if quote_currency == 'usdt': symbolsList.append(data['symbol']) amplitudeModelList = [] lineLen = 2000 for symbol in symbolsList: lastClose = 0 kLine = huobi.get_kline(symbol, '15min', lineLen) if kLine is None: continue print(symbol) if kLine['status'] == 'ok' and kLine['data'] and len( kLine['data']) >= lineLen: kLine['data'].reverse() else: continue amplitudeList = [] for data in kLine['data']:
pairList.append(pairs) tranPairsList = [] count = 0 for symbolPair in pairList: try: first = symbolPair[0] second = symbolPair[1] # if count == 5: # break # count = count + 1 #1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year firstLine = huobi.get_kline(first, '15min', 2000) secondLine = huobi.get_kline(second, '15min', 2000) # print(firstLine,first) # print(secondLine,second) if firstLine is None or secondLine is None: continue if firstLine['status'] == 'ok' and secondLine[ 'status'] == 'ok' and firstLine['data'] and secondLine[ 'data']: firstLine['data'].reverse() secondLine['data'].reverse()
import HuobiService as huobi if __name__ == '__main__': # A EOS B HT C USDT firstLine = huobi.get_kline('htusdt', '1min', 2000) secondLine = huobi.get_kline('eosusdt', '1min', 2000) threeLine = huobi.get_kline('eosht', '1min', 2000) firstData = firstLine['data'] secondData = secondLine['data'] threeData = threeLine['data'] firstData.reverse() secondData.reverse() threeData.reverse() usdt = 0 ht = 5 eos = 5 balance = 0 buyAmount = 50 fei = 0 for i in range(0, 2000): p1 = float(firstData[i]['close']) p2 = float(secondData[i]['close']) p3 = float(threeData[i]['close']) if (p2 / p1 - p3) > (p3 * 0.003): eos += buyAmount # 买入 EOS
global lastBuy global buynum isSend = False if buy== 0: if (D<K and lastK<lastD or J>100 ) : isSend = True if J < lastJ and J>50 and J>K: isSend = True return isSend if __name__ == '__main__': test = huobi.get_kline('eosusdt','1min',1000) test['data'].reverse() for i in test['data']: get_KDJ(i,test['data'].index(i),'init') lastId = 0 count = 0 lastDate = huobi.get_kline('eosusdt','1min',1) while True: try: test = huobi.get_kline('eosusdt','1min',1) test['data'].reverse() logging.info(test['data'])
cash = pd.Series(cash, index=position.index) shareY = pd.Series(shareY, index=position.index) shareX = pd.Series(shareX, index=position.index) asset = cash + shareY * priceY + shareX * priceX account = pd.DataFrame({ 'Position': position, 'ShareY': shareY, 'ShareX': shareX, 'Cash': cash, 'Asset': asset }) return (account) if __name__ == '__main__': firstLine = huobi.get_kline('xlmusdt', '1min', 100) secondLine = huobi.get_kline('omgusdt', '1min', 100) firstLine['data'].reverse() secondLine['data'].reverse() firstData = [] secondData = [] firstCount = 0 secondCount = 0 balance = 0 score = [] firstClose = 0 secondClose = 0 ratioList = [] b = 0
lastK.append(K) lastJ.append(J) lastD.append(D) if len(lastK)>10: lastK = lastK[1:] lastD = lastD[1:] lastJ = lastJ[1:] last100.append(data['close']) last100.sort() if len(last100) >101: last100 = last100[1:] return isBuy if __name__ == '__main__': test = huobi.get_kline('eosusdt','1min',100) test['data'].reverse() for i in test['data']: judgeBuy(i,test['data'].index(i))
train_df = train_df[1:] train_df = train_df.reset_index(drop=True) train_df['label'] = label select_feat = [ 'open', 'high', 'low', 'close', 'vol', 'amount', 'count', 'oc', 'lh' ] label_df = pd.DataFrame(index=train_df.index, columns=["label"]) label_df["label"] = np.log(train_df["label"]) train_df = train_df[select_feat] def rmse(y_true, y_pred): return np.sqrt(mean_squared_error(y_true, y_pred)) regr = xgb.XGBRegressor(colsample_bytree=0.5, gamma=0.0, learning_rate=0.01, max_depth=6, min_child_weight=1.5, n_estimators=2200, reg_alpha=0.9, reg_lambda=0.6, subsample=0.8, seed=2018, silent=1) regr.fit(train_df, label_df) return regr if __name__ == '__main__': print(HuobiService.get_kline('btcusdt', '1min', 1))
import HuobiService as huobi import pandas as pd import numpy as np import matplotlib.pyplot as plt from arch.unitroot import ADF def zscore(series): return (series - series.mean()) / np.std(series) if __name__ == '__main__': firstLine = huobi.get_kline('ctxcusdt', '15min', 2000) secondLine = huobi.get_kline('hcusdt', '15min', 2000) firstLine['data'].reverse() secondLine['data'].reverse() firstData = [] secondData = [] firstCount = 0 secondCount = 0 balance = 0 score = [] firstClose = 0 secondClose = 0 ratioList = [] b = 0 c = 0 mu = 0
transactionModels = refresh.getAllPairAndRefresh() if env != "pro": checkOrderStatusThread.doCheck(transactionModels) lastDataDict = commonUtil.lastDataDict lastIdDict = commonUtil.lastIdDict try: for transactionModel in transactionModels: lastData = lastDataDict.get(transactionModel.symbol, []) lastId = lastIdDict.get(transactionModel.symbol, 0) if len(lastData) == 0: lastData = huobi.get_kline(transactionModel.symbol, transactionModel.period, 1) #{'ch': 'market.xrpusdt.kline.1min', 'status': 'ok', 'ts': 1587722033132, # 'data': [{'open': 0.19629, 'id': 1587721980, 'count': 29, 'amount': 36697.23, 'close': 0.1963, 'vol': 7200.5755178, 'high': 0.1963, 'low': 0.19613}]} thisData = huobi.get_kline(transactionModel.symbol, transactionModel.period, 1) if thisData['status'] == 'ok' and thisData['data'] and len( thisData['data']) >= 1: thisData['data'].reverse() else: continue if env == "pro": logUtil.info(thisData['data'], transactionModel.symbol) logUtil.kLineData(transactionModel.symbol + "-->" +
import MAUtil as mAUtil import commonUtil as commonUtil import BiTradeUtil as biTradeUtil import fileOperUtil as fileOperUtil import BollUtil as bollUtil import AmountUtil as amountUtil import logUtil if __name__ == '__main__': transactionModels = modelUtil.getAllPair() env = "dev" lastIndex = 0 for transactionModel in transactionModels: logUtil.info(transactionModel) kline = huobi.get_kline(transactionModel.symbol, transactionModel.period, 2000) datas = kline['data'] datas.reverse() for data in datas: commonUtil.addSymbol(data ,transactionModel) kdjFlag = kDJUtil.judgeBuy(transactionModel.symbol) rSIFlag = rSIUtil.rsiJudgeBuy(transactionModel.symbol,12) maFlag = mAUtil.maJudgeBuy(data,transactionModel.symbol) avgFlag = commonUtil.juideAllGap(data['close'],transactionModel.symbol,transactionModel.tradeGap) highFlag = commonUtil.juideHighest(data['close'],transactionModel.symbol) bollFlag = bollUtil.judgeBoll(data['close'],transactionModel.symbol) lowFlag = commonUtil.juideLowest(data['close'],transactionModel.symbol) riskFlag = amountUtil.judgeRisk(transactionModel.symbol)
import TradeUtil as TradeUtil import time import logging # 1.初始化日志默认配置 logging.basicConfig( filename='./my.log', # 日志输出文件 level=logging.INFO, # 日志写入级别 datefmt='%Y-%m-%d %H:%M:%S', # 时间格式 format='%(asctime)s Line:%(lineno)s==>%(message)s') # 日志写入格式 if __name__ == '__main__': symbols = 'eosusdt' bi = 'eos' env = "dev" test = huobi.get_kline(symbols, '1min', 2000) test['data'].reverse() # a = test['data'][:1000] # b = test['data'][1000:] for data in test['data']: index = test['data'].index(data) close = data['close'] priceUtil.add(data, index) KDJ.calKDJ(data, index) # for data in a: # index = a.index(data) # close = data['close']
import matplotlib.pyplot as plt import HuobiService as huobi import pandas as pd import numpy as np from arch.unitroot import ADF def zscore(series): return (series - series.mean()) / np.std(series) if __name__ == '__main__': firstLine = huobi.get_kline('ontusdt', '15min', 2000) secondLine = huobi.get_kline('btsusdt', '15min', 2000) firstLine['data'].reverse() secondLine['data'].reverse() firstData = [] secondData = [] for index in range( min(len(firstLine['data']) - 1000, len(secondLine['data']) - 1000)): firstData.append(firstLine['data'][index]['close']) secondData.append(secondLine['data'][index]['close']) X = pd.Series(firstData, name='X') Y = pd.Series(secondData, name='Y') pd.concat([Y], axis=1).plot(figsize=(10, 7)) pd.concat([X], axis=1).plot(figsize=(10, 7)) # (X / Y).plot(figsize=(10, 7))
# -*- coding: utf-8 -*- import HuobiService as huobi import spot_api as spot if __name__ == '__main__': api_key = 'fe31ff24-fcf3-4160-81e9-69f1d0509dc3' spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True) test = spotAPI.get_kline('eos-USDT', '', '', 60) data = test data.reverse() print(data) test2 = huobi.get_kline('eosusdt', '1min', 200) data2 = test2['data'] data2.reverse() print(data2) count = 0 amount = 1 for i in range(0, 200): close1 = float(data[i][4]) close2 = float(data2[i]['close']) if close1 > close2: fei = close1 * 0.0015 + close2 * 0.002 gap = close1 - close2 if gap > fei:
def checkGetKline(): symbol = request.args.get("symbol") period = request.args.get("period") size = request.args.get("size", type=int, default=150) #print symbol,period,size infos = HuobiService.get_kline(symbol, period, size) #print infos klines = [] times = [] buyLimit = [] sellLimit = [] curTime = datetime.datetime.now() #print curTime for item in infos["data"]: tmp = [] tmp.append(item["open"]) tmp.append(item["close"]) tmp.append(item["low"]) tmp.append(item["high"]) buyLimit.append(0) sellLimit.append(0) klines.append(tmp) #times.append(time.strftime("%d %M"),curTime) times.append(curTime.strftime("%m-%d %H")) if period == "30min": curTime -= datetime.timedelta(minutes=1) elif period == "60min": curTime -= datetime.timedelta(hours=1) elif period == "1day": curTime -= datetime.timedelta(days=1) #print times klines.reverse() times.reverse() matchresults = getMatchresults() matchRecords = [] for item in matchresults["data"]: #print item["created-at"] timeTmp = time.strftime("%m-%d %H", time.localtime(item["created-at"] / 1000)) index = times.index(timeTmp) #print index if item["type"] == "buy-limit": buyLimit[index] = item["filled-amount"] elif item["type"] == "sell-limit": sellLimit[index] = item["filled-amount"] tmpItem = [] tmpItem.append(item["type"]) tmpItem.append( time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(item["created-at"] / 1000))) tmpItem.append(item["filled-amount"]) tmpItem.append(item["filled-fees"]) tmpItem.append(item["price"]) matchRecords.append(tmpItem) return jsonify({ "klines": klines, "times": times, "buy-limit": buyLimit, "sell-limit": sellLimit, "matchRecords": matchRecords })
isSend = False if buy== 0: if (D<K and lastK<lastD or J>100 ) : isSend = True if J < lastJ and J>50 and J>K: isSend = True return isSend if __name__ == '__main__': fig = plt.figure() symbols = 'eosusdt' test = huobi.get_kline(symbols,'1min',2000) # test = aa.test0 test['data'].reverse() # test = client.getKline(1200,"eos_usdt") xmajorLocator = MultipleLocator(100); klineXY = get_kline_xy(test['data']) klinex = klineXY[0] kliney = klineXY[1] MA60XY = get_MA(test['data'],60) MA30XY = get_MA(test['data'],30) MA10XY = get_MA(test['data'],5)
def exposed_get_kline(self, symbol, period, size): return hb.get_kline(symbol, period, size)