def layout(self, parent): ######## lf = LabelFrame(parent, text='Logs') self.scr = scrolledtext.ScrolledText(lf)#, width=100, height=30) self.scr.pack(fill=BOTH, expand=YES) lf.pack(side=LEFT,fill=BOTH, expand=YES) ######## lf = LabelFrame(parent, text='Status') if cfg.is_future(): lf1 = LabelFrame(lf, text='user_info',labelanchor=W) self.infolist = Label(lf1, text='', width=25, height=25, padx=2, pady=10, anchor=NW, justify=LEFT) self.infolist.pack() lf1.pack(side=TOP,fill=X, expand=YES) if cfg.is_future(): lf2 = LabelFrame(lf, text='position',labelanchor=W) self.positionlist = Label(lf2, text='', width=25, height=25, padx=2, pady=10, anchor=NW, justify=LEFT) self.positionlist.pack() lf2.pack(side=TOP,fill=X, expand=YES) lf.pack(side=LEFT,fill=BOTH, expand=YES) self.handle_robot_status(0) ######### lf = LabelFrame(parent, text='Paramters') lf.pack(side=LEFT,fill=BOTH, expand=YES) ######### lf = LabelFrame(parent, text='Action') ttk.Button(lf,text='start',command=self.start).pack() ttk.Button(lf,text='stop',command=self.stop).pack() ttk.Button(lf,text='testback',command=self.testback).pack() lf.pack(side=LEFT,fill=BOTH, expand=YES) ##### sslot.register_robot_status(self.handle_robot_status) sslot.register_robot_log(self.handle_robot_log)
def kline(self, symbol, dtype, size = 0, since = 0): params = {'symbol':symbol, 'type':dtype, 'size':size, 'since':since} if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() url = cfg.get_url() + OKCoinBase.RESOURCES_URL['kline'].format('future_' if cfg.is_future() else '') #print(url, params) data = self._request.get(url, params) ## t o h l c v a for i in range(len(data)): data[i][0] = data[i][0]/1000 return data
def depth(self, symbol, size=0, merge=0): """return: asks :卖方深度 bids :买方深度 """ params = {'symbol':symbol, 'size':size, 'merge':merge} if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() url = cfg.get_url() + OKCoinBase.RESOURCES_URL['depth'].format('future_' if cfg.is_future() else '') return self._request.get(url, params)
def batch_trade(self, symbol, orders_data): params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'orders_data':orders_data } if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() params['lever_rate'] = 10 res = OKCoinBase.RESOURCES_URL['batch_trade'].format('future_' if cfg.is_future() else '') return self._signed_request(params, res)
def depth(self, symbol, size=0, merge=0): """return: asks :卖方深度 bids :买方深度 """ params = {'symbol': symbol, 'size': size, 'merge': merge} if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() url = cfg.get_url() + OKCoinBase.RESOURCES_URL['depth'].format( 'future_' if cfg.is_future() else '') return self._request.get(url, params)
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 batch_trade(self, symbol, orders_data): params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'orders_data': orders_data } if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() params['lever_rate'] = 10 res = OKCoinBase.RESOURCES_URL['batch_trade'].format( 'future_' if cfg.is_future() else '') return self._signed_request(params, res)
def orders_info(self, symbol, order_id): params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'order_id': order_id } if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() res = OKCoinBase.RESOURCES_URL['orders_info'].format('future_' if cfg.is_future() else '') ret = self._signed_request(params, res) if ret['result'] == True: return ret['orders'] else: return None
def trades(self, symbol): """return: amount:交易数量 date_ms:交易时间(毫秒) date:交易时间 price:交易价格 tid:交易ID type:交易类型 """ params = {'symbol':symbol} if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() url = cfg.get_url() + OKCoinBase.RESOURCES_URL['trades'].format('future_' if cfg.is_future() else '') return self._request.get(url, params)
def trades(self, symbol): """return: amount:交易数量 date_ms:交易时间(毫秒) date:交易时间 price:交易价格 tid:交易ID type:交易类型 """ params = {'symbol': symbol} if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() url = cfg.get_url() + OKCoinBase.RESOURCES_URL['trades'].format( 'future_' if cfg.is_future() else '') return self._request.get(url, params)
def orders_info(self, symbol, order_id): params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'order_id': order_id } if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() res = OKCoinBase.RESOURCES_URL['orders_info'].format( 'future_' if cfg.is_future() else '') ret = self._signed_request(params, res) if ret['result'] == True: return ret['orders'] else: return None
def order_info(self, symbol, order_id, status, current_page=1, page_length=50): """params: status String 否 查询状态 1:未完成的订单 2:已经完成的订单 order_id String 是 订单ID -1:查询指定状态的订单,否则查询相应订单号的订单 current_page String 否 当前页数 page_length String 否 每页获取条数,最多不超过50 return: { orders:[{ amount: 委托数量 contract_name: 合约名称 create_date: 委托时间 deal_amount: 成交数量 fee: 手续费 order_id: 订单ID price: 订单价格 price_avg: 平均价格 status: 订单状态(0等待成交 1部分成交 2全部成交 -1撤单 4撤单处理中 5撤单中) symbol: btc_usd ltc_usd eth_usd etc_usd bch_usd type: 订单类型 1:开多 2:开空 3:平多 4: 平空 unit_amount:合约面值 lever_rate: 杠杆倍数 value:10\20 默认10 }] result:... } """ params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'status': status, 'order_id': order_id, 'current_page': current_page, 'page_length': page_length } if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() res = OKCoinBase.RESOURCES_URL['order_info'].format( 'future_' if cfg.is_future() else '') ret = self._signed_request(params, res) if ret['result'] == True: return ret['orders'] else: return None
def kline(self, symbol, dtype, size=0, since=0): params = { 'symbol': symbol, 'type': dtype, 'size': size, 'since': since } if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() url = cfg.get_url() + OKCoinBase.RESOURCES_URL['kline'].format( 'future_' if cfg.is_future() else '') #print(url, params) data = self._request.get(url, params) ## t o h l c v a for i in range(len(data)): data[i][0] = data[i][0] / 1000 return data
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 ticker(self, symbol): """return: buy:买一价 contract_id:合约ID high:最高价 last:最新成交价 low:最低价 sell:卖一价 unit_amount:合约面值 vol:成交量(最近的24小时) """ params = {'symbol':symbol} if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() url = cfg.get_url() + OKCoinBase.RESOURCES_URL['ticker'].format('future_' if cfg.is_future() else '') return self._request.get(url, params)['ticker']
def ticker(self, symbol): """return: buy:买一价 contract_id:合约ID high:最高价 last:最新成交价 low:最低价 sell:卖一价 unit_amount:合约面值 vol:成交量(最近的24小时) """ params = {'symbol': symbol} if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() url = cfg.get_url() + OKCoinBase.RESOURCES_URL['ticker'].format( 'future_' if cfg.is_future() else '') return self._request.get(url, params)['ticker']
def order_info(self, symbol, order_id, status, current_page=1, page_length=50): """params: status String 否 查询状态 1:未完成的订单 2:已经完成的订单 order_id String 是 订单ID -1:查询指定状态的订单,否则查询相应订单号的订单 current_page String 否 当前页数 page_length String 否 每页获取条数,最多不超过50 return: { orders:[{ amount: 委托数量 contract_name: 合约名称 create_date: 委托时间 deal_amount: 成交数量 fee: 手续费 order_id: 订单ID price: 订单价格 price_avg: 平均价格 status: 订单状态(0等待成交 1部分成交 2全部成交 -1撤单 4撤单处理中 5撤单中) symbol: btc_usd ltc_usd eth_usd etc_usd bch_usd type: 订单类型 1:开多 2:开空 3:平多 4: 平空 unit_amount:合约面值 lever_rate: 杠杆倍数 value:10\20 默认10 }] result:... } """ params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'status':status, 'order_id':order_id, 'current_page':current_page, 'page_length':page_length } if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() res = OKCoinBase.RESOURCES_URL['order_info'].format('future_' if cfg.is_future() else '') ret = self._signed_request(params, res) if ret['result'] == True: return ret['orders'] else: return None
def trade(self, symbol, price, amount, trade_type, match_price): """return: order_id : 订单ID result : true代表成功返回 """ params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'price': price, 'amount': amount, 'type': trade_type, 'match_price': match_price } if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() params['lever_rate'] = 10 res = OKCoinBase.RESOURCES_URL['trade'].format('future_' if cfg.is_future() else '') ret = self._signed_request(params, res) if ret['result'] == True: return True ##ret['order_id'] else: return False
def user_info(self): """return: { info:{ xxx:{ account_rights:账户权益 keep_deposit:保证金 profit_real:已实现盈亏 profit_unreal:未实现盈亏 risk_rate:保证金率 } ... } result:... } or 4fix return: { info:{ xxx:{ balance:账户余额(可用保证金) contracts:[{ available:合约可用(可用保证金) balance:账户(合约)余额 bond:固定保证金(已用保证金) contract_id:合约ID contract_type:合约类别 freeze:冻结保证金 profit:已实现盈亏 unprofit:未实现盈亏 }] rights:账户权益 } ... } result:... } """ params = {'api_key': cfg.get_id()} if cfg.is_future(): res = OKCoinBase.RESOURCES_URL[ 'user_info' if cfg.is_future_mode_all( ) else 'user_info_4fix'].format('future_') else: res = OKCoinBase.RESOURCES_URL['user_info'] ret = self._signed_request(params, res) if ret['result'] == True: return ret['info'] else: log.err("user_info ret:%s" % ret) return None
def trade(self, symbol, price, amount, trade_type, match_price): """return: order_id : 订单ID result : true代表成功返回 """ params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'price': price, 'amount': amount, 'type': trade_type, 'match_price': match_price } if cfg.is_future(): params['contract_type'] = cfg.get_future_contract_type() params['lever_rate'] = 10 res = OKCoinBase.RESOURCES_URL['trade'].format( 'future_' if cfg.is_future() else '') ret = self._signed_request(params, res) if ret['result'] == True: return True ##ret['order_id'] else: return False
def user_info(self): """return: { info:{ xxx:{ account_rights:账户权益 keep_deposit:保证金 profit_real:已实现盈亏 profit_unreal:未实现盈亏 risk_rate:保证金率 } ... } result:... } or 4fix return: { info:{ xxx:{ balance:账户余额(可用保证金) contracts:[{ available:合约可用(可用保证金) balance:账户(合约)余额 bond:固定保证金(已用保证金) contract_id:合约ID contract_type:合约类别 freeze:冻结保证金 profit:已实现盈亏 unprofit:未实现盈亏 }] rights:账户权益 } ... } result:... } """ params = {'api_key': cfg.get_id()} if cfg.is_future(): res = OKCoinBase.RESOURCES_URL['user_info' if cfg.is_future_mode_all() else 'user_info_4fix'].format('future_') else: res = OKCoinBase.RESOURCES_URL['user_info'] ret = self._signed_request(params, res) if ret['result'] == True: return ret['info'] else: log.err("user_info ret:%s"%ret) return None
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_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 get_all_pair(self): pairs = [] data = None try: if cfg.get_cfg_plat() == 'coinex': if False: data = cet.acquire_market_list() pairs = [item.lower() for item in data] else: coin1 = [ 'btc', 'ltc', 'eth', 'etc', 'bch', 'btg', 'xrp', 'eos' ] coin2 = ['usdt'] for i in coin1: for j in coin2: if i == j: continue else: pairs.append(i + j) elif cfg.get_cfg_plat() == 'fcoin': pass elif cfg.get_cfg_plat() == 'okex': if cfg.is_future(): coin1 = [ 'btc', 'ltc', 'eth', 'etc', 'bch', 'btg', 'xrp', 'eos' ] coin2 = ['usd'] else: coin1 = ['btc', 'eth', 'etc', 'bch', 'ltc', 'okb'] coin2 = ['usdt', 'btc', 'eth', 'okb'] for i in coin1: for j in coin2: if i == j: continue else: pairs.append(i + "_" + j) else: pass except: log.err("Exception on get_all_pair! data:%s" % data) return pairs
def get_all_pair(self): pairs = [] data = None try: if cfg.get_cfg_plat() == 'coinex': if False: data = cet.acquire_market_list() pairs = [item.lower() for item in data] else: coin1 = ['btc','ltc','eth','etc','bch','btg','xrp','eos'] coin2 = ['usdt'] for i in coin1: for j in coin2: if i == j: continue else: pairs.append(i+j) elif cfg.get_cfg_plat() == 'fcoin': pass elif cfg.get_cfg_plat() == 'okex': if cfg.is_future(): coin1 = ['btc','ltc','eth','etc','bch','btg','xrp','eos'] coin2 = ['usd'] else: coin1 = ['btc','eth','etc','bch','ltc','okb'] coin2 = ['usdt', 'btc', 'eth','okb'] for i in coin1: for j in coin2: if i == j: continue else: pairs.append(i+"_"+j) else: pass except: log.err("Exception on get_all_pair! data:%s"%data) return pairs
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