def trade(self, timestamp, signal, bp, ba, sp, sa): price = amount = 0 if signal == 'buy': #if cfg.get_cfg_plat() == 'okex': if cfg.is_future(): if self.future_position['sell_available'] > 0: #orders = fwk.list_orders(cfg.get_pair(), -1, 1) # #if len(orders) > 0: # for o in orders: # if o['type'] == self.trade_type['margin_sell']: type_key = 'margin_sell' price = sp amount = min(sa, self.future_position['sell_available']) else: contracts = self.user_info[cfg.get_coin1()]['contracts'][0] a = contracts['available'] - (contracts['available'] + contracts['bond']) * 0.9 if a > contracts['available']*0.01: ##避免手续费导致的总量减少造成误差 price = sp amount = min(sa, a * cfg.get_future_buy_lever()) type_key = 'open_buy' else: pass #elif cfg.get_cfg_plat() == 'coinex': # pass elif signal == 'sell': #if cfg.get_cfg_plat() == 'okex': if cfg.is_future(): if self.future_position['buy_available'] > 0: #orders = fwk.list_orders(cfg.get_pair(), -1, 1) # #if len(orders) > 0: # for o in orders: # if o['type'] == self.trade_type['margin_sell']: type_key = 'margin_buy' price = bp amount = min(ba, self.future_position['buy_available']) else: contracts = self.user_info[cfg.get_coin1()]['contracts'][0] a = contracts['available'] - (contracts['available'] + contracts['bond']) * 0.9 if a > contracts['available']*0.01: ##避免手续费导致的总量减少造成误差 price = bp amount = min(ba, a * cfg.get_future_sell_lever()) type_key = 'open_sell' else: ###spot have no sell type pass #elif cfg.get_cfg_plat() == 'coinex': # pass else: ## standby pass if price > 0 and amount > 0: log.info("going to trade! type:%s price:%f, amount:%f"%(type_key, price, amount)) self._trade(timestamp, type_key, price, amount)
def handle_robot_status(self, status): c1_info = self.rbt.user_info[cfg.get_coin1()] text = '' for i in c1_info.keys(): if i == 'contracts': for j in c1_info[i][0].keys(): val = c1_info[i][0][j] if isinstance(val, str): text += j+': '+val+'\n' else: text += j+': '+str(round(val, 6))+'\n' else: val = c1_info[i] if isinstance(val, str): text += i+': '+val+'\n' else: text += i+': '+str(round(val, 6))+'\n' self.infolist.config(text=text) text = '' if cfg.is_future(): for i in self.rbt.future_position.keys(): val = self.rbt.future_position[i] if isinstance(val, str): text += i+': '+val+'\n' else: text += i+': '+str(round(val, 6))+'\n' self.positionlist.config(text=text)
def _update_balance(self): handles = self.data_handles['balance'] handles['data'][0] = fwk.get_balance(cfg.get_coin1()) handles['data'][1] = fwk.get_balance(cfg.get_coin2()) 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 _trade(self,timestamp, type_key, price, amount, match_price=0): ttype = self.trade_type[type_key] if self.simulate: ret = True else: ret = True #fwk.trade(cfg.get_pair(), ttype, price, amount, match_price) if ret == True: trade_param = [timestamp, type_key, price, amount, match_price] self.update_variables(trade_param) info = self.user_info[cfg.get_coin1()]['contracts'][0] sslot.robot_log("%s profit:%d, unprofit:%d"%(trade_param, info['profit'], info['unprofit'])) if self.testing == False: sslot.robot_status(1)
def update_profit(self, price): if self.simulate: if cfg.is_future(): position = self.future_position if position['buy_amount'] > 0: position['buy_profit_lossratio'] = (price - position['buy_price_avg'])/position['buy_price_avg'] position['buy_profit_real'] = position['buy_profit_lossratio'] * position['buy_amount'] else: position['buy_profit_lossratio'] = position['buy_profit_real'] = 0 if position['sell_amount'] > 0: position['sell_profit_lossratio'] = (position['sell_price_avg'] - price)/position['sell_price_avg'] position['sell_profit_real'] = position['sell_profit_lossratio'] * position['sell_amount'] else: position['sell_profit_lossratio'] = position['sell_profit_real'] = 0 self.user_info[cfg.get_coin1()]['contracts'][0]['unprofit'] = position['buy_profit_real'] + position['sell_profit_real']
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_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 __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
def withdraw_info(self, symbol, withdraw_id): params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'withdraw_id': withdraw_id } res = OKCoinBase.RESOURCES_URL['withdraw_info'] return self._signed_request(params, res) okb = OKCoinAPI() if __name__ == '__main__': #print(okb.ticker(cfg.get_pair())) #print(okb.depth(cfg.get_pair(), 5, 0)) #print(okb.kline(cfg.get_pair(), '1hour', 10)) #print(okb.trades(cfg.get_pair())) #print(okb.future_index(cfg.get_pair())) #print(okb.future_exchange_rate()) #print(okb.future_estimated_price(cfg.get_pair())) #print(okb.future_hold_amount(cfg.get_pair())) #print(okb.future_price_limit(cfg.get_pair())) print(okb.user_info()) #print(okb.trade(cfg.get_pair(), 1, 1, 1, 0)) #print(okb.order_info(cfg.get_pair(), -1, 1, 1, 50)) print(okb.future_position(cfg.get_coin1())) #print(okb.future_trades_history(cfg.get_pair(), "2018-08-01", 0)) #print(okb.future_explosive(cfg.get_pair(), 0, 1, 1, 50))
return self._signed_request(params, res) def withdraw_info(self, symbol, withdraw_id): params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'withdraw_id': withdraw_id } res = OKCoinBase.RESOURCES_URL['withdraw_info'] return self._signed_request(params, res) okb = OKCoinAPI() if __name__ == '__main__': #print(okb.ticker(cfg.get_pair())) #print(okb.depth(cfg.get_pair(), 5, 0)) #print(okb.kline(cfg.get_pair(), '1hour', 10)) #print(okb.trades(cfg.get_pair())) #print(okb.future_index(cfg.get_pair())) #print(okb.future_exchange_rate()) #print(okb.future_estimated_price(cfg.get_pair())) #print(okb.future_hold_amount(cfg.get_pair())) #print(okb.future_price_limit(cfg.get_pair())) print(okb.user_info()) #print(okb.trade(cfg.get_pair(), 1, 1, 1, 0)) #print(okb.order_info(cfg.get_pair(), -1, 1, 1, 50)) print(okb.future_position(cfg.get_coin1())) #print(okb.future_trades_history(cfg.get_pair(), "2018-08-01", 0)) #print(okb.future_explosive(cfg.get_pair(), 0, 1, 1, 50))