def get_hilo(self): i = 0 while i < 100: try: hilos = turtle.HILO() result = hilos.publish_current_hilo_price() # result = prediction.publish_current_limit_price(periods="1H") sell = float(result[1]) buy = float(result[0]) close = float(result[2]) # the close price of last hour high = float(result[3]) low = float(result[4]) quits = float(result[5]) quitl = float(result[6]) inhourbuy = float(result[7]) inhoursell = float(result[8]) return ([ sell, buy, close, high, low, quits, quitl, inhourbuy, inhoursell ]) except Exception: print(Exception) predict.print_and_write('Try to get hilo again') time.sleep(10) i += 1 continue
def checkP(self): p = self.bitflyer_api.getpositions(product_code='FX_BTC_JPY') position0 = 0.0 if isinstance(p, list): for i in p: if i['side'] == 'SELL': i['size'] = -i['size'] position0 += i['size'] if abs(i['size'] - self.position) < 0.001: predict.print_and_write('Real position is same as program one') self.real_position = position0 return (0) if isinstance(p, dict) or len(p) == 0: if abs(self.position) < 0.001: predict.print_and_write('Position not exist') self.real_position = position0 return (0) predict.print_and_write('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') str = 'Position is unusual. Check!!! position :%f, program: %f' % ( position0, self.position) predict.print_and_write(str) self.sendamail('position check failed', str) predict.print_and_write('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') return (1)
def get_collateral(self): try: result = self.bitflyer_api.getcollateral(product_code='FX_BTC_JPY') data2csv.data2csv(result) predict.print_and_write(result) except Exception: predict.print_and_write(Exception)
def get_checkin_price(self): p = self.bitflyer_api.getpositions(product_code='FX_BTC_JPY') position0 = 0.0 checkin_price = 0.0 time_diff = 0 if isinstance(p, list): for i in p: #predict.print_and_write('check in price: %f' % (i['price'])) if i['side'] == 'SELL': position0 -= i['size'] else: position0 += i['size'] for i in p: checkin_price += i['size'] / abs(position0) * i['price'] predict.print_and_write('Check in price: %f, position: %f' % (checkin_price, position0)) for i in p: opentime = i['open_date'] time_diff = self.bf_timejudge(opentime) break elif isinstance(p, dict) or len(p) == 0: predict.print_and_write('Position not exist') checkin_price = math.floor(checkin_price) return ([checkin_price, position0, time_diff])
def cancle_order(self, id): product = 'FX_BTC_JPY' i = 20 while i>0: try: statue = self.bitflyer_api.cancelparentorder(product_code=product, parent_order_acceptance_id=id) time.sleep(10) order = self.get_orderbyid(id) child_order = self.bitflyer_api.getchildorders(product_code=product, parent_order_id =order['parent_order_id']) if child_order != []: self.bitflyer_api.cancelchildorder(product_code=product, child_order_id=child_order['child_order_id']) if order['parent_order_state'] == 'CANCELED': predict.print_and_write('Order cancelled') remain_amount = float(order['cancel_size']) return(remain_amount) else: i -= 1 print('Try again cancelling') continue except Exception: order = self.get_orderbyid(id) if order['parent_order_state'] == 'COMPLETED': print('Executed before cancelling') return(0.0) time.sleep(5) print('Exception Try again cancelling') i -= 1 predict.print_and_write('Cancel order failed') self.sendamail('Cancel order failed','cancel failed : id %s'%(id)) return([])
def judge_overshoot(self, hilo, starttime): tdelta = self.bf_timejudge(starttime) ready = False overshoot_s = False overshoot_l = False while tdelta < 3600: cur_price = self.get_current_price(50) if ready: print('Ready to trade: price: %f' % cur_price, end='\r') else: print('Price: %f' % cur_price, end='\r') # hilo0 lo hilo1 hi if cur_price > hilo[0] and cur_price < hilo[1]: ready = True elif cur_price < hilo[0] - self.ovrshoot and ready: overshoot_s = True elif cur_price > hilo[1] + self.ovrshoot and ready: overshoot_l = True time.sleep(0.8) tdelta = self.bf_timejudge(starttime) if overshoot_l: predict.print_and_write('Detected a long trade:') return 'long' elif overshoot_s: predict.print_and_write('Detected a short trade:') return 'short' return 'none'
def trial_order(self, checkins, trial_loss_cut, starttime): # Trial order keep loss less than trial_loss_cut profit = 0 max_profit = 0 pre_profit = -trial_loss_cut atr = trial_loss_cut tdelta = self.bf_timejudge(starttime) startt = tdelta predict.print_and_write('Use a trial order') #predict.print_and_write('Current position: %f, price: %f' % (checkins[1], checkins[0])) while tdelta < 3600: cur_price = self.get_current_price(50) if checkins[1] > 0: profit = cur_price - checkins[0] elif checkins[1] < 0: profit = checkins[0] - cur_price if profit > max_profit: max_profit = profit if max_profit > atr * 0.5 and max_profit < atr and atr > 5000: trial_loss_cut = atr * 0.5 elif max_profit >= atr and max_profit < atr * 2: trial_loss_cut = atr elif max_profit >= atr * 2: trial_loss_cut = max_profit / 2 if trial_loss_cut > 15000: trial_loss_cut = 15000 dt = tdelta - startt if profit < pre_profit: # quit if checkins[1] > 0.0: trade_mount = '%.2f' % abs(checkins[1]) order = self.trade_market('sell', trade_mount, int(cur_price)) predict.print_and_write(order) elif checkins[1] < 0.0: trade_mount = '%.2f' % abs(checkins[1]) order = self.trade_market('buy', trade_mount, int(cur_price)) predict.print_and_write(order) predict.print_and_write( 'Quit position ,profit: %.2f, time: %d' % (profit, dt)) return elif profit >= pre_profit and profit > 0: temp_pre_profit = profit - trial_loss_cut if temp_pre_profit > pre_profit: pre_profit = temp_pre_profit print('T: %d, P: %5.0f, MP: %5.0f, L: %5.0f' % (dt, profit, max_profit, pre_profit), end='\r') time.sleep(0.8) tdelta = self.bf_timejudge(starttime) predict.print_and_write('Time is over, quit, final profit: %5.0f' % (profit))
def maintance_time(self): while 1: cur_oclock = int(time.strftime('%H:')[0:-1]) cur_min = int(time.strftime('%M:')[0:-1]) if (cur_oclock == 4 and cur_min >= 0 and cur_min <= 12) or (cur_oclock == 3 and cur_min >= 58): predict.print_and_write('Server maintenance') time.sleep(60) continue else: return
def get_collateral(self): try: result = self.bitflyer_api.getcollateral(product_code='FX_BTC_JPY') self.total_margin = float(result['collateral']) self.useable_margin = self.total_margin - self.least_collateral print('Useable for trading: %.0f' % self.useable_margin) data2csv.data2csv(result) predict.print_and_write(result) except Exception: predict.print_and_write(Exception)
def trade_stop(self, type, price, amount): self.maintance_time() product = 'FX_BTC_JPY' print('trade bitflyer') expire_time = 575 try_t = 0 while try_t < 20: if type == 'BUY' or type == 'buy': parameters = [{ 'product_code': product, 'condition_type': 'STOP', 'side': 'BUY', 'trigger_price': str(price - 500), 'size': str(amount) }] order = self.bitflyer_api.sendparentorder( order_method='SIMPLE', minute_to_expire=expire_time, parameters=parameters) data2csv.data2csv([ time.strftime('%b:%d:%H:%M'), 'order', 'BUY_STOP', 'amount', '%f' % float(amount) ]) predict.print_and_write('Buy stop market %f at %f' % (float(amount), price - 500)) elif type == "SELL" or type == "sell": parameters = [{ 'product_code': product, 'condition_type': 'STOP', 'side': 'SELL', 'trigger_price': str(price + 500), 'size': str(amount) }] order = self.bitflyer_api.sendparentorder( order_method='SIMPLE', minute_to_expire=expire_time, parameters=parameters) data2csv.data2csv([ time.strftime('%b:%d:%H:%M'), 'order', 'SELL_STOP', 'amount', '%f' % float(amount) ]) predict.print_and_write('Sell stop market %f at %f' % (float(amount), price + 500)) else: print("error!") if 'parent_order_acceptance_id' in order: return (order) else: try_t += 1 print(order) print('Failed, try again') time.sleep(20)
def judge_condition(self): # judge position at hour start. time.sleep(1) starttime = time.gmtime(self.get_curhour()) cur_price = self.get_current_price(100) predict.print_and_write( '##################################################') predict.print_and_write('Start a new hour: Current price: %f' % (cur_price)) hilo = self.get_hilo() time.sleep(1) atr = self.get_ATR() self.ovrshoot = atr * 0.25 self.trade_in_hour(starttime, hilo, atr)
def judge_condition(self): if self.order_exist == True: remain_test = self.cancel_order(self.order_id) + 1 print('cancel order, remain %f' % (remain_test - 1)) result = self.get_hilo() hi = result[1] lo = result[0] if lo > hi: temp = 0 temp = lo lo = hi hi = temp predict.print_and_write('Lo > hi, switch, Lo: %f, Hi: %f' % (lo, hi)) checkins = self.get_checkin_price() # if not position exist trade none position if checkins[1] == 0.0: predict.print_and_write('No position exist, trade none position') cur_price = self.get_current_price(100) predict.print_and_write('current price is %f' % (cur_price)) self.trade_none_position(cur_price, hi, lo) # else trade in position else: data2csv.data2csv([ time.strftime('%b:%d:%H:%M'), 'position', '%f' % float(checkins[1]), 'check in price', '%f' % float(checkins[0]) ]) predict.print_and_write('Position exist, trade with position') close = result[2] self.trade_with_position(hi, lo, close)
def checkposition(self,placed): product_code = 'FX_BTC_JPY' time.sleep(20) order0 = self.get_orderbyid(self.order_places['id']) x = order0['cancel_size'] if abs(x - self.order_places['remain']) > 0.001: str = 'Order is unusual. Check!!! cancel size :%f, remain: %f' % (x, self.order_places['remain']) predict.print_and_write(str) self.sendamail('order check failed', str) # position0 = self.bitflyer_api.getcollateral() # if abs(self.position - position0['open_position_pnl']) > 0.001: # predict.print_and_write('position check failed') amount = placed['size'] - placed['executed_size'] - self.order_places['remain'] if abs(amount) > 0.001: predict.print_and_write('Trading occured during detecing and cancelling') if self.order_places['type'] == 'buy': predict.print_and_write('%f has been brought'%amount) self.position += amount self.tradeamount -= amount * self.order_places['trade_price'] else: predict.print_and_write('%f has been sold'%amount) self.position -= amount self.tradeamount += amount * self.order_places['trade_price']
def get_ATR(self): i = 0 while i < 100: try: atrs = technical_fx_hilo2.HILO() result = atrs.getATR() # result = prediction.publish_current_limit_price(periods="1H") return (result) except Exception: print(Exception) predict.print_and_write('Try to get atr again') time.sleep(10) i += 1 continue
def detect_in_one_tunit(self, waiting_time, detect_fre, price ,slide = 20): self.wave_times = 0 init_oclock = int(time.strftime('%H:')[0:-1]) for i in range(0, detect_fre): time.sleep(waiting_time / (detect_fre + 1)) cur_oclock = int(time.strftime('%H:')[0:-1]) cur_min = int(time.strftime('%M:')[0:-1]) if (cur_oclock == 4 and cur_min >= 0 and cur_min <= 11) or (cur_oclock == 3 and cur_min >= 59): predict.print_and_write('Server maintenance') continue if cur_oclock != init_oclock: # if oclock changed regenerate the buy and sell price and retrading result = prediction.publish_current_limit_price(periods="1H") sell = float(result[1]) buy = float(result[0]) #sell = price + self.order_places['slide'] #buy = price - self.order_places['slide'] predict.print_and_write('................................') predict.print_and_write('Oclcok change from %d to %d, price changed to buy %f, sell %f'%(init_oclock, cur_oclock, buy, sell)) init_oclock = cur_oclock oid = autoTrading.onTrick_trade(buy, sell, slide) else: predict.print_and_write('.') sell = price + self.order_places['slide'] buy = price - self.order_places['slide'] oid = autoTrading.detect_trade(buy, sell, slide) if oid == -1 or oid == -2: print(oid) return(oid) #predict.print_and_write('Detect finished, waiting for another detection') time.sleep(waiting_time / (detect_fre + 1)) return(self.wave_times)
def judge_condition(self): # judge position at hour start. time.sleep(1) starttime = time.gmtime(self.get_curhour()) checkins = self.get_checkin_price() suggest_position = checkins[1] predict.print_and_write('Check in price: %f, position: %f' % (checkins[0], checkins[1])) cur_price = self.get_current_price(100) predict.print_and_write('Current price: %f' % (cur_price)) hilo = self.get_hilo() # if keep a position and transfor in this hour. ckeck position again: if (checkins[1] != 0.0 and self.switch_in_hour) or checkins[1] == 0.0: if checkins[1] == 0.0: predict.print_and_write( 'No position exist, trade none position') else: predict.print_and_write( 'Trade with position %f and init position' % checkins[1]) suggest_position = self.trade_hour_init(checkins, cur_price, hilo) #self.order_id = order['parent_order_acceptance_id'] # we should verify the order is dealing or not here self.judge_position(suggest_position) #order = self.update_order(checkins, hilo) self.trade_in_hour(suggest_position, starttime, hilo)
def trade_bitflyer_constoplimit(self, type, buysellprice, amount, slide=100): while 1: cur_oclock = int(time.strftime('%H:')[0:-1]) cur_min = int(time.strftime('%M:')[0:-1]) if (cur_oclock == 4 and cur_min >= 0 and cur_min <= 11) or (cur_oclock == 3 and cur_min >= 59): predict.print_and_write('Server maintenance') time.sleep(60) continue else: break product = 'FX_BTC_JPY' print('trade bitflyer') expire_time = 75 if type == 'BUY' or type == 'buy': # order = self.quoinex_api.create_market_buy(product_id=5, quantity=str(amount), price_range=str(buysellprice)) parameters = [{ 'product_code': product, 'condition_type': 'STOP_LIMIT', 'side': 'BUY', 'price': str(buysellprice + slide), 'size': str(amount), 'trigger_price': str(buysellprice) }] order = self.bitflyer_api.sendparentorder( order_method='SIMPLE', minute_to_expire=expire_time, parameters=parameters) elif type == "SELL" or type == "sell": parameters = [{ 'product_code': product, 'condition_type': 'STOP_LIMIT', 'side': 'SELL', 'price': str(buysellprice - slide), 'size': str(amount), 'trigger_price': str(buysellprice) }] order = self.bitflyer_api.sendparentorder( order_method='SIMPLE', minute_to_expire=expire_time, parameters=parameters) else: print("error!") return (order)
def trade_market(self, type, amount, wprice=10000): self.maintance_time() product = 'FX_BTC_JPY' print('trade bitflyer') expire_time = 575 try_t = 0 while try_t < 20: if type == 'BUY' or type == 'buy': order = self.bitflyer_api.sendchildorder( product_code=product, child_order_type='MARKET', side='BUY', size=str(amount)) data2csv.data2csv([ time.strftime('%b:%d:%H:%M'), 'order', 'BUY_MARKET', 'amount', '%f' % float(amount) ]) predict.print_and_write('Buy market ' + str(amount)) elif type == "SELL" or type == "sell": order = self.bitflyer_api.sendchildorder( product_code=product, child_order_type='MARKET', side='SELL', size=str(amount)) data2csv.data2csv([ time.strftime('%b:%d:%H:%M'), 'order', 'SELL_MARKET', 'amount', '%f' % float(amount) ]) predict.print_and_write('Sell market ' + str(amount)) else: print("error!") if 'child_order_acceptance_id' in order: time.sleep(2) execute_price = self.get_execute_order() if execute_price != 0: if type == "SELL" or type == "sell": slides = float(wprice) - float(execute_price) predict.print_and_write( 'SELL : Wish price: %f, deal price: %f, slide : %f' % (wprice, execute_price, slides)) notify.notify_it('SELL : Price: %f, amount : %f' % (wprice, float(amount))) elif type == "BUY" or type == "buy": slides = float(execute_price) - float(wprice) predict.print_and_write( 'BUY : Wish price: %f, deal price: %f, slide : %f' % (wprice, execute_price, slides)) notify.notify_it('BUY : Price: %f, amount : %f' % (wprice, float(amount))) return order else: try_t += 1 print(order) print('Failed, try again') time.sleep(20)
def handel_partly_deal(self, order): # if order is partly dealed, the state should be 'COMPLETED' however executed size is not full size. pflag = self.checkP() real_executed_size = abs(self.position - pflag) if order['parent_order_state'] == 'COMPLETED' and order[ 'executed_size'] != order['size']: if self.order_places['remain'] - order['executed_size'] >= 0.01: order['executed_size'] = self.order_places['remain'] if abs(order['executed_size'] - real_executed_size) > 0.001: predict.print_and_write( 'Maybe double executed, real: %f, executed: %f' % (real_executed_size, order['executed_size'])) return (-1) else: order['executed_size'] = real_executed_size return (order)
def trade_hour_init(self, checkins, cur_price, hilo): # if we have a new position in this hour self.switch_in_hour = False if hilo[2] >= hilo[1]: # if close > hi and position is negative #TODO trade_mount = self.init_trade_amount - checkins[1] if trade_mount > 0.0: amount_str = '%.2f' % (trade_mount) self.trade_market('buy', amount_str) predict.print_and_write('Switch to long') amount_stop = '%.2f' % (self.init_trade_amount * 2) order = self.trade_stop('sell', hilo[0], amount_stop) self.order_exist = True # buy self.init + checkins[1] elif hilo[2] <= hilo[0]: # if close < lo and position is positive # TODO # sell self.init + checkins[1] trade_mount = self.init_trade_amount + checkins[1] if trade_mount > 0.0: amount_str = '%.2f' % (trade_mount) self.trade_market('sell', amount_str) predict.print_and_write('Switch to short') amount_stop = '%.2f' % (self.init_trade_amount * 2) order = self.trade_stop('buy', hilo[1], amount_stop) self.order_exist = True elif cur_price > hilo[0] and cur_price < hilo[1]: predict.print_and_write('Switch to middle') # TODO if checkins[1] < 0.0: # TODO trade_mount = '%.2f' % (abs(checkins[1])) self.trade_market('buy', trade_mount) predict.print_and_write('Buy short back') time.sleep(3) elif checkins[1] > 0.0: # TODO # sell back trade_mount = '%.2f' % (abs(checkins[1])) self.trade_market('sell', trade_mount) predict.print_and_write('Sell long back') time.sleep(3) # set an oco order = self.trade_oco1(hilo[1], hilo[0], self.init_trade_amount) self.order_exist = True return (order)
def judge_order(self, id): i = 20 while i > 0: try: order = self.get_orderbyid(id) if order['parent_order_state'] == 'REJECTED': predict.print_and_write('Order rejected') return True else: return False except Exception: time.sleep(5) print(Exception) print('Exception Try again') i -= 1 predict.print_and_write('Try many times but no result, return False without confidence') return False
def get_hilo(self): i = 0 while i < 30: try: hilos = technical_fx_bidirc.HILO() result = hilos.publish_current_hilo_price(periods="15m") # result = prediction.publish_current_limit_price(periods="1H") sell = float(result[1]) buy = float(result[0]) close = float(result[2]) # the close price of last hour return([sell, buy, close]) except Exception: print(Exception) predict.print_and_write('Try to get hilo again') time.sleep(10) i+=1 continue
def cancle_order(self, id): product = 'FX_BTC_JPY' i = 20 while i > 0: try: statue = self.bitflyer_api.cancelparentorder( product_code=product, parent_order_acceptance_id=id) time.sleep(10) order = self.get_orderbyid(id) if order['parent_order_state'] == 'COMPLETED': predict.print_and_write('Order completed') return (0.0) if order['parent_order_state'] == 'CANCELED': predict.print_and_write('Order cancelled') if order['parent_order_type'] == 'OCO': pflag = self.checkP() real_executed_size = abs(self.position - pflag) if real_executed_size > self.order_places['remain']: predict.print_and_write('maybe double executed') predict.print_and_write( 'real: %f, executed: %f, pre_remain: %f' % (real_executed_size, order['executed_size'], self.order_places['remain'])) remain_amount = float( order['cancel_size']) - self.order_places['remain'] else: remain_amount = float(order['cancel_size']) return (remain_amount) else: i -= 1 print('Try again cancelling') continue except Exception: order = self.get_orderbyid(id) if order['parent_order_state'] == 'COMPLETED': print('Executed before cancelling') return (0.0) time.sleep(5) print('Exception Try again cancelling') i -= 1 predict.print_and_write('Cancel order failed') self.sendamail('Cancel order failed', 'cancel failed : id %s' % (id)) return ([])
def trade_oco1(self, buy, sell, amount): self.maintance_time() product = 'FX_BTC_JPY' print('trade bitflyer') expire_time = 575 try_t = 0 while try_t < 20: parameters = [ { 'product_code': product, 'condition_type': 'STOP', 'side': 'BUY', 'size': str(amount), 'trigger_price': str(buy) }, { 'product_code': product, 'condition_type': 'STOP', 'side': 'SELL', 'size': str(amount), 'trigger_price': str(sell) }, ] order = self.bitflyer_api.sendparentorder( order_method='OCO', minute_to_expire=expire_time, parameters=parameters) data2csv.data2csv([ time.strftime('%b:%d:%H:%M'), 'order', 'OCO_STOP', 'amount', '%f' % float(amount), 'buy', '%f' % float(buy), 'sell', '%f' % float(sell) ]) predict.print_and_write( 'OCO stopmarket buy: %f, sell %f, amount %f' % (float(buy), float(sell), float(amount))) if 'parent_order_acceptance_id' in order: return (order) else: try_t += 1 print(order) print('Failed, try again') time.sleep(20)
def trade_in_hour(self, initposition, starttime): trial_loss_cut = 1500 # if the dynamic loss touches 2000, quit position. time.sleep(1) self.switch_in_hour = False tdelta = self.bf_timejudge(starttime) while tdelta < 3600: checkins = self.get_checkin_price() new_position = float('%.2f' % (checkins[1])) if initposition != 0 and new_position * initposition < 0: self.switch_in_hour = True elif initposition == 0.0 and new_position != 0.0: self.switch_in_hour = True if self.switch_in_hour: predict.print_and_write('switch in hour') self.trial_order(checkins, trial_loss_cut, starttime) self.switch_in_hour = False else: print('.') time.sleep(60) tdelta = self.bf_timejudge(starttime)
def trade_market(self, type, amount): self.maintance_time() product = 'FX_BTC_JPY' print('trade bitflyer') expire_time = 575 try_t = 0 while try_t < 20: if type == 'BUY' or type == 'buy': order = self.bitflyer_api.sendchildorder( product_code=product, child_order_type='MARKET', side='BUY', size=str(amount)) data2csv.data2csv([ time.strftime('%b:%d:%H:%M'), 'order', 'BUY_MARKET', 'amount', '%f' % float(amount) ]) predict.print_and_write('Buy market ' + amount) elif type == "SELL" or type == "sell": order = self.bitflyer_api.sendchildorder( product_code=product, child_order_type='MARKET', side='SELL', size=str(amount)) data2csv.data2csv([ time.strftime('%b:%d:%H:%M'), 'order', 'SELL_MARKET', 'amount', '%f' % float(amount) ]) predict.print_and_write('Sell market ' + amount) else: print("error!") if 'child_order_acceptance_id' in order: return (order) else: try_t += 1 print(order) print('Failed, try again') time.sleep(20)
def update_order(self, checkins, hilo): order = '' if checkins[1] < 0.0: # TODO # buy double trade_mount = self.init_trade_amount - checkins[1] if trade_mount > 0.0: amount_str = '%.2f' % (trade_mount) order = self.trade_stop('buy', hilo[1], amount_str) predict.print_and_write('Update a buy stop order') self.order_exist = True elif checkins[1] > 0.0: # TODO # sell double trade_mount = self.init_trade_amount + checkins[1] if trade_mount > 0.0: amount_str = '%.2f' % (trade_mount) order = self.trade_stop('sell', hilo[0], amount_str) predict.print_and_write('Update a sell stop order') self.order_exist = True return order
def cancel_order(self, id): product = 'FX_BTC_JPY' i = 20 while i > 0: try: statue = self.bitflyer_api.cancelparentorder( product_code=product, parent_order_acceptance_id=id) time.sleep(10) order = self.get_orderbyid(id) if order['parent_order_state'] == 'COMPLETED': predict.print_and_write('Order completed') return (0.0) if order['parent_order_state'] == 'CANCELED': predict.print_and_write('Order cancelled') return (float(order['cancel_size'])) else: i -= 1 print('Try again cancelling') continue except Exception: order = self.get_orderbyid(id) if order['parent_order_state'] == 'COMPLETED': print('Executed before cancelling') return (0.0) time.sleep(5) print('Exception Try again cancelling') i -= 1 predict.print_and_write('Cancel failed,( May be just lag)') return (0.0)
def judge_condition(self): # judge position at hour start. time.sleep(1) starttime = time.gmtime(self.get_curhour()) checkins = self.get_checkin_price() suggest_position = checkins[1] predict.print_and_write( '##################################################') cur_price = self.get_current_price(100) predict.print_and_write('Start a new hour: Current price: %f' % (cur_price)) predict.print_and_write('Check in price: %.0f, position: %.2f' % (checkins[0], checkins[1])) hilo = self.get_hilo() time.sleep(3) atr = round(float(self.get_ATR()), 0) self.decide_trade_amount(cur_price, atr * 2.2) # if keep a position and transfor in this hour. ckeck position again: if (checkins[1] != 0.0 and self.switch_in_hour) or checkins[1] == 0.0: if checkins[1] == 0.0: predict.print_and_write( 'No position exist, trade none position') else: predict.print_and_write( 'Trade with position %f and init position' % checkins[1]) suggest_position = self.trade_hour_init(checkins, cur_price, hilo) #self.order_id = order['parent_order_acceptance_id'] # we should verify the order is dealing or not here checkins = self.judge_position(suggest_position) #order = self.update_order(checkins, hilo) if checkins[1] != 0.0: if checkins[1] > 0.0: last_peak = hilo[3] self.get_stop_acc_line(atr, checkins, last_peak) else: last_peak = hilo[4] self.get_stop_acc_line(atr, checkins, last_peak) self.trade_in_hour(suggest_position, starttime, hilo, atr)
def inhour_processing(self, hi, lo, checkin, i): stopprofit = checkin trade_amount = '%.2f' % (abs(self.cur_hold_position)) traed_amount_switch = '%.2f' % (float(trade_amount) + self.init_trade_amount) # counter last for 20 min # First order if self.cur_hold_position < 0.0: stoploss = hi order = self.trade_oco3('short', stopprofit, stoploss, trade_amount, traed_amount_switch) else: stoploss = lo order = self.trade_oco3('long', stopprofit, stoploss, trade_amount, traed_amount_switch) while i > 0: predict.print_and_write('Detecting inhour switch, last %d times'%(int(i))) catchup_trial = 0.43 time.sleep(60) checkins = self.get_checkin_price() new_position = float('%.2f' % (math.floor(checkins[1] * 100) / 100)) trade_amount = '%.2f' % (abs(self.cur_hold_position)) traed_amount_switch = '%.2f' % (float(trade_amount) + self.init_trade_amount) if new_position * self.cur_hold_position < 0: # if position changed place a new order. self.cur_hold_position = new_position if new_position > 0.0: predict.print_and_write('Place a sell order') stoploss = math.floor(stopprofit * (100 - catchup_trial) / 100) order = self.trade_oco3('long', stopprofit, stoploss, trade_amount, traed_amount_switch) else: predict.print_and_write('Place a buy order') stoploss = math.floor(stopprofit * (100 + catchup_trial) / 100) order = self.trade_oco3('short', stopprofit, stoploss, trade_amount, traed_amount_switch) i -= 1 return(order)