def testback(self): self.testing = True self.trade_history.drop(self.trade_history.index, inplace=True) #clear history days = 10 kl_1hour = fwk.get_kline(cfg.get_pair(), dtype="1hour", limit=min(days*24, 2000)) if kl_1hour.size > 0: self.bbands.handle_data(kl_1hour) self.macd.handle_data(kl_1hour) self.stoch.handle_data(kl_1hour) if True: kl_5min = fwk.get_kline(cfg.get_pair(), dtype="5min", limit=min(days*24*60/5, 2000)) if(kl_5min.size <= 0): return p = kl_5min['c'] t = kl_5min['t'] else: p = kl_1hour['c'] t = kl_1hour['t'] for i in range(t.size): dummy_depth = {'buy':[[p[i]*0.999, 1000]],'sell':[[p[i]*1.001, 1000]]} self.handle_depth(t[i], dummy_depth) log.dbg("test done... user_info:%s"%(self.user_info)) log.dbg("test done... future_position:%s"%(self.future_position)) sslot.trade_history(self.trade_history) sslot.robot_status(1) self.testing = False
def _update_kline_without_timer(self, *notuse): handles = self.data_handles['kline'] handles['data'] = fwk.get_kline(cfg.get_pair(), dtype="1hour", limit=min(self.days * 24, 2000)) if handles['data'].size > 0: for f in handles['func']: f(handles['data'])
def _update_price(self): handles = self.data_handles['price'] handles['data'] = fwk.get_price(cfg.get_pair()) if handles['data'] != None and len(handles['data']) > 0: for f in handles['func']: f(handles['data']) if handles['reg'] > 0: handles['thandle'] = threading.Timer(handles['tperiod'], handles['tfunc']) handles['thandle'].start()
def buy_order(self): pair = cfg.get_pair() percentage = cfg.get_cfg('buy_percentage') price_less = cfg.get_cfg('buy_price_less') buy_type = cfg.get_cfg('buy_type') price_decimal_limit = cfg.get_cfg('price_decimal_limit') amount_decimal_limit = cfg.get_cfg('amount_decimal_limit') amount_limit = cfg.get_cfg('amount_limit') price = digits(fwk.get_last_price(cfg.get_pair())*(1.0-price_less),price_decimal_limit) av = fwk.get_balance(cfg.get_coin2())['available'] amount = digits(av / price * percentage, amount_decimal_limit) if amount < amount_limit: log.err("Fail buy! amount=%f available=%f limit=%f"%(amount, av, amount_limit)) return log.info("creating buy order... pair:%s price:%f amount:%f"%(cfg.get_pair(), price, amount)) try: #fwk.buy(pair, price, amount, buy_type) log.info("success") except: log.err("Fail create buy order!")
def _update_depth(self): handles = self.data_handles['depth'] #t1 = time.time() handles['data'] = fwk.get_depth(cfg.get_pair()) t = time.time() #print(int(t-t1)) #time consume if handles['data'] != None and len(handles['data']) > 0: for f in handles['func']: f(t, handles['data']) if handles['reg'] > 0: handles['thandle'] = threading.Timer(handles['tperiod'], handles['tfunc']) handles['thandle'].start()
def sell_order(self): percentage = cfg.get_cfg('sell_percentage') price_more = cfg.get_cfg('sell_price_more') sell_type = cfg.get_cfg('sell_type') price_decimal_limit = cfg.get_cfg('price_decimal_limit') amount_decimal_limit = cfg.get_cfg('amount_decimal_limit') amount_limit = cfg.get_cfg('amount_limit') price = digits(fwk.get_last_price(cfg.get_pair())*(1.0+price_more),price_decimal_limit) av = fwk.get_balance(cfg.get_coin1())['available'] amount = digits(av * percentage, amount_decimal_limit) if amount < amount_limit and av >= amount_limit: amount = amount_limit elif amount > av or av < amount_limit: log.err("Fail sell! amount=%f available=%f limit=%f"%(amount, av, amount_limit)) return log.info("going to create sell order... pair:%s price:%f amount:%f"%(cfg.get_pair(), price, amount)) try: #fwk.sell(pair, price, amount, sell_type) log.info("success") except: log.err("Fail create sell order!")
def _update_kline(self): handles = self.data_handles['kline'] handles['data'] = fwk.get_kline(cfg.get_pair(), dtype="1hour", limit=min(self.days*24, 2000)) #print("_update_kline", handles['data']) if handles['data'].size > 0: for f in handles['func']: f(handles['data']) else: ##fail get kline handles['thandle'] = threading.Timer(1, handles['tfunc']) handles['thandle'].start() return if handles['reg'] > 0: period = handles['tperiod'] - int(time.time())%handles['tperiod'] + 1 #local time currently, will use server time to improve handles['thandle'] = threading.Timer(period, handles['tfunc']) handles['thandle'].start()
def param_select_layout(self, parent): #self.plat = 'coinex' #self.pair = 'btc_usdt' indicator_opt = ['bbands','macd', 'stoch','bbands+macd', 'stoch+macd'] idx = indicator_opt.index(cfg.get_indicator()) self.add_frame_combobox(parent, indicator_opt, idx, self.indicator_select, side=LEFT) plat_opt = ['coinex','okex'] idx = plat_opt.index(cfg.get_cfg_plat()) self.add_frame_combobox(parent, plat_opt, idx, self.plat_select, side=LEFT) pair_opt = fwk.get_all_pair() idx = pair_opt.index(cfg.get_pair()) self.add_frame_combobox(parent, pair_opt, idx, self.pair_select, side=LEFT) future_or_spot_opt = ['future','spot'] idx = 0 if cfg.is_future() else 1 self.add_frame_combobox(parent, future_or_spot_opt, 0, self.future_or_spot_select, side=LEFT)
def _update_kline(self): handles = self.data_handles['kline'] handles['data'] = fwk.get_kline(cfg.get_pair(), dtype="1hour", limit=min(self.days * 24, 2000)) #print("_update_kline", handles['data']) if handles['data'].size > 0: for f in handles['func']: f(handles['data']) else: ##fail get kline handles['thandle'] = threading.Timer(1, handles['tfunc']) handles['thandle'].start() return if handles['reg'] > 0: period = handles['tperiod'] - int(time.time()) % handles[ 'tperiod'] + 1 #local time currently, will use server time to improve handles['thandle'] = threading.Timer(period, handles['tfunc']) handles['thandle'].start()
def print_price(self): try: price = fwk.get_last_price(cfg.get_pair()) print("'%s' current price:%f"%(cfg.get_pair(), price)) except: print("Fail get '%s' price!"%(cfg.get_pair()))
def __init__(self): self.simulate = True if cfg.is_future(): self.user_info = { cfg.get_coin1():{ 'balance':0, #账户余额(可用保证金) 'contracts':[{ 'available':100, #合约可用(可用保证金) 'balance':0, #账户(合约)余额 'bond':0, #固定保证金(已用保证金) 'contract_id':0, #合约ID 'contract_type':0, #合约类别 'freeze':0, #冻结保证金 'profit':0, #已实现盈亏 'unprofit':0, #未实现盈亏 }], 'rights':0, #账户权益 } } self.future_position = { 'buy_amount':0, #多仓数量 'buy_available':0, #多仓可平仓数量 'buy_bond':0, #多仓保证金 'buy_flatprice':0, #多仓强平价格 'buy_profit_lossratio':0, #多仓盈亏比 'buy_price_avg':0, #开仓平均价 'buy_price_cost':0, #结算基准价 'buy_profit_real':0, #多仓已实现盈余 'contract_id':0, #合约id 'contract_type':0, #合约类型 'create_date':0, #创建日期 'sell_amount':0, #空仓数量 'sell_available':0, #空仓可平仓数量 'sell_bond':0, #空仓保证金 'sell_flatprice':0, #空仓强平价格 'sell_profit_lossratio':0, #空仓盈亏比 'sell_price_avg':0, #开仓平均价 'sell_price_cost':0, #结算基准价 'sell_profit_real':0, #空仓已实现盈余 'symbol':cfg.get_pair(), #btc_usd ltc_usd eth_usd etc_usd bch_usd 'lever_rate':cfg.get_future_buy_lever() #杠杆倍数 } #variables for mine self.coin1_fee=0.0 self.coin2_fee=0.0 self.order_id = [] self.deficit_allowed = cfg.get_fee() * cfg.get_trans_fee() self.exchange = 0 #variables for trade record self.price_history = pd.DataFrame(columns=['t','p']) self.trade_history = pd.DataFrame(columns=['t','type', 'price', 'amount', 'match_price']) self.trade_type = {'open_buy':1, 'open_sell':2, 'loss_buy':3, 'loss_sell':4, 'margin_buy':3,'margin_sell':4} #variables for technical indicator self.bbands = Bbands() self.macd = Macd() self.stoch = Stoch() #variables for log print self.n_depth_handle = 0 #variables for automatic running self.running = 0 #variables for test back self.testing = False
pass except: log.err("Exception on get_user_info!") return info def get_future_position(self, pair): pos = defaultdict(lambda: None) try: if cfg.get_cfg_plat() == 'coinex': pass elif cfg.get_cfg_plat() == 'fcoin': pass elif cfg.get_cfg_plat() == 'okex': pos = okb.future_position(pair) else: pass except: log.err("Exception on get_future_position!") return pos fwk = framework() if __name__ == '__main__': #print(fwk.get_price(cfg.get_pair())) from datetime import datetime kl = fwk.get_kline(cfg.get_pair(), '1hour', 10, 1536235000000) for i in kl.index: kl['t'][i] = datetime.fromtimestamp(kl['t'][i]) print(kl) #print(fwk.get_depth(cfg.get_pair()))
else: pass except: log.err("Exception on get_user_info!") return info def get_future_position(self, pair): pos = defaultdict(lambda: None) try: if cfg.get_cfg_plat() == 'coinex': pass elif cfg.get_cfg_plat() == 'fcoin': pass elif cfg.get_cfg_plat() == 'okex': pos = okb.future_position(pair) else: pass except: log.err("Exception on get_future_position!") return pos fwk = framework() if __name__ == '__main__': #print(fwk.get_price(cfg.get_pair())) from datetime import datetime kl = fwk.get_kline(cfg.get_pair(), '1hour', 10, 1536235000000) for i in kl.index: kl['t'][i] = datetime.fromtimestamp(kl['t'][i]) print(kl) #print(fwk.get_depth(cfg.get_pair()))
def _update_kline_without_timer(self, *notuse): handles = self.data_handles['kline'] handles['data'] = fwk.get_kline(cfg.get_pair(), dtype="1hour", limit=min(self.days*24, 2000)) if handles['data'].size > 0: for f in handles['func']: f(handles['data'])
def print_depth(self): try: depth = fwk.get_depth(cfg.get_pair()) print(depth) except: print("Fail get '%s' depth!"%(cfg.get_pair()))
def cancel_order(self): return fwk.cancel_order(cfg.get_pair())
def update_variables(self, trade_param): if self.trade_history.index.size > 100: self.trade_history = self.trade_history.drop(0) self.trade_history.loc[self.trade_history.index.size] = trade_param ##may need use append instead if self.testing == False: sslot.trade_history(self.trade_history) hist.info("%s"%(trade_param)) if self.simulate: param = self.trade_history.iloc[-1] a = param['amount'] * (1-0.001) ##take off trans fee info_contracts = self.user_info[cfg.get_coin1()]['contracts'][0] position = self.future_position if param['type'] == 'open_buy': if cfg.is_future(): oldfund = position['buy_amount'] * position['buy_price_avg'] newfund = a * param['price'] position['buy_amount'] += a position['buy_available'] += a position['buy_price_avg'] = (oldfund + newfund) / position['buy_amount'] position['buy_bond'] += a/position['lever_rate'] info_contracts['available'] -= param['amount']/position['lever_rate'] info_contracts['bond'] += a/position['lever_rate'] if param['type'] == 'margin_buy': if cfg.is_future(): position['buy_amount'] -= param['amount'] position['buy_available'] -= param['amount'] position['buy_bond'] -= param['amount']/position['lever_rate'] info_contracts['available'] += a/position['lever_rate'] info_contracts['bond'] -= param['amount']/position['lever_rate'] profit = (param['price'] - position['buy_price_avg'])/position['buy_price_avg'] * a info_contracts['profit'] += profit info_contracts['available'] += profit self.update_profit(param['price']) if param['type'] == 'open_sell': if cfg.is_future(): oldfund = position['sell_amount'] * position['sell_price_avg'] newfund = param['amount'] * param['price'] position['sell_amount'] += a position['sell_available'] += a position['sell_price_avg'] = (oldfund + newfund) / position['sell_amount'] position['sell_bond'] += a/position['lever_rate'] info_contracts['available'] -= param['amount']/position['lever_rate'] info_contracts['bond'] += a/position['lever_rate'] if param['type'] == 'margin_sell': if cfg.is_future(): position['sell_amount'] -= param['amount'] position['sell_available'] -= param['amount'] position['sell_bond'] -= param['amount']/position['lever_rate'] info_contracts['available'] += a/position['lever_rate'] info_contracts['bond'] -= param['amount']/position['lever_rate'] profit = (position['sell_price_avg'] - param['price'])/position['sell_price_avg'] * a info_contracts['profit'] += profit info_contracts['available'] += profit self.update_profit(param['price']) log.dbg("user_info:%s"%(self.user_info)) log.dbg("future_position:%s"%(self.future_position)) else: if cfg.get_cfg_plat() == '': #reserve pass else: if cfg.is_future(): self.user_info = fwk.get_user_info() self.future_position = fwk.get_future_position(cfg.get_pair()) log.dbg("user_info:%s"%(self.user_info)) log.dbg("future_position:%s"%(self.future_position)) else: pass
def list_order(self): order_list = fwk.list_orders(cfg.get_pair()) for i in range(len(order_list)): print(order_list[i])