def buy(self, symbol, quantity, buyPrice): # Do you have an open order? self.check_order() try: # Create order if self.buy_order_type == 'limit': orderId = Orders.buy_limit(symbol, quantity, buyPrice) else: orderId = Orders.buy_market(symbol, quantity, buyPrice) # Database log Database.write([ orderId, symbol, 0, buyPrice, 'BUY', quantity, self.option.profit ]) print('Buy order created id:%d, q:%.8f, p:%.8f' % (orderId, quantity, float(buyPrice))) self.order_id = orderId return orderId except Exception as e: print('bl: %s' % (e)) time.sleep(self.WAIT_TIME_BUY_SELL) return None
def place_order(): ''' Function used to help the user enter a new order''' userOption = int(input((PLACE_ORDER_TEXT))) if ( userOption == 1): # User already has a product index print("user option 1") productIndex = int(input("Enter the index of the product you want to order: ")) try: products = Products.load_products() today = date.today().strftime(f"%d/%m/%Y") if 0 < productIndex <= products.__len__(): product_to_order = products[productIndex - 1] quantity = 0 loop = True while loop: quantity = int(input("Enter the quantity: \n")) if quantity > 0: loop = False shippingAddress = input("Please write the address where this order should be delivered:\n") # Order ( product , date, quantity, address) clientOrder = Order(product_to_order.__dict__, today, quantity, shippingAddress) Orders.add_order(clientOrder) input(f"Your order has been placed! " + READ_ENTER_KEY) except JSONDecodeError: input("Error on retrieving the products. Try again later. " + READ_ENTER_KEY) elif ( userOption == 2): # User wants to first see the products list display_products() # After he checked out the products ask why again which one he wants for his order place_order() elif ( userOption == 3 ): # User simply wants to go back input(READ_ENTER_KEY)
def stop(self, symbol, quantity, orderId, last_price): # If the target is not reached, stop-loss. stop_order = Orders.get_order(symbol, orderId) stopprice = self.calc(float(stop_order['price'])) lossprice = stopprice - (stopprice * self.stop_loss / 100) status = stop_order['status'] # Order status if status == 'NEW' or status == 'PARTIALLY_FILLED': if self.cancel(symbol, orderId): # Stop loss if last_price >= lossprice: sello = Orders.sell_market(symbol, quantity) #print('Stop-loss, sell market, %s' % (last_price)) self.logger.info('Stop-loss, sell market, %s' % (last_price)) sell_id = sello['orderId'] if sello == True: return True else: # Wait a while after the sale to the loss. time.sleep(self.WAIT_TIME_STOP_LOSS) statusloss = sello['status'] if statusloss != 'NEW': print('Stop-loss, sold') self.logger.info('Stop-loss, sold') return True else: self.cancel(symbol, sell_id) return False else: sello = Orders.sell_limit(symbol, quantity, lossprice) print('Stop-loss, sell limit, %s' % (lossprice)) time.sleep(self.WAIT_TIME_STOP_LOSS) statusloss = sello['status'] if statusloss != 'NEW': print('Stop-loss, sold') return True else: self.cancel(symbol, sell_id) return False else: print('Cancel did not work... Might have been sold before stop loss...') return True elif status == 'FILLED': self.order_id = 0 self.order_data = None print('Order filled') return True else: return False
def stop(self, symbol, quantity, orderId, last_price): # If the target is not reached, stop-loss. stop_order = Orders.get_order(symbol, orderId) stopprice = self.calc(float(stop_order['price'])) lossprice = stopprice - (stopprice * self.stop_loss / 100) status = stop_order['status'] # Order status if status == 'NEW' or status == 'PARTIALLY_FILLED': if self.cancel(symbol, orderId): # Stop loss if last_price >= lossprice: sello = Orders.sell_market(symbol, quantity) print('Stop-loss, sell market, %s' % (last_price)) sell_id = sello['orderId'] if sello == True: return True else: # Wait a while after the sale to the loss. time.sleep(self.WAIT_TIME_STOP_LOSS) statusloss = sello['status'] if statusloss != 'NEW': print('Stop-loss, sold') return True else: self.cancel(symbol, sell_id) return False else: sello = Orders.sell_limit(symbol, quantity, lossprice) print('Stop-loss, sell limit, %s' % (lossprice)) time.sleep(self.WAIT_TIME_STOP_LOSS) statusloss = sello['status'] if statusloss != 'NEW': print('Stop-loss, sold') return True else: self.cancel(symbol, sell_id) return False else: print( 'Cancel did not work... Might have been sold before stop loss...' ) return True elif status == 'FILLED': self.order_id = 0 self.order_data = None print('Order filled') return True else: return False
def check(self, symbol, orderId, quantity): # If profit is available and there is no purchase from the specified price, take it with the market. # Do you have an open order? self.check_order() trading_size = 0 time.sleep(self.WAIT_TIME_BUY_SELL) while trading_size < self.MAX_TRADE_SIZE: # Order info order = Orders.get_order(symbol, orderId) side = order['side'] price = float(order['price']) # TODO: Sell partial qty orig_qty = float(order['origQty']) self.buy_filled_qty = float(order['executedQty']) status = order['status'] #print('Wait buy order: %s id:%d, price: %.8f, orig_qty: %.8f' % (symbol, order['orderId'], price, orig_qty)) self.logger.info('Wait buy order: %s id:%d, price: %.8f, orig_qty: %.8f' % (symbol, order['orderId'], price, orig_qty)) if status == 'NEW': if self.cancel(symbol, orderId): buyo = Orders.buy_market(symbol, quantity) #print('Buy market order') self.logger.info('Buy market order') self.order_id = buyo['orderId'] self.order_data = buyo if buyo == True: break else: trading_size += 1 continue else: break elif status == 'FILLED': self.order_id = order['orderId'] self.order_data = order #print('Filled') self.logger.info('Filled') break elif status == 'PARTIALLY_FILLED': #print('Partial filled') self.logger.info('Partial filled') break else: trading_size += 1 continue
def validate(self): valid = True symbol = self.option.symbol filters = self.filters()['filters'] minQty = float(filters['LOT_SIZE']['minQty']) minPrice = float(filters['PRICE_FILTER']['minPrice']) minNotional = float(filters['MIN_NOTIONAL']['minNotional']) quantity = float(self.option.quantity) lastPrice = float(Orders.get_ticker(symbol)['lastPrice']) # minNotional defines minimum amount a coin can be bought self.min_notional = minNotional # stepSize defines the intervals that a quantity/icebergQty can be increased/decreased by. self.step_size = self.get_satoshi_count( float(filters['LOT_SIZE']['stepSize'])) # tickSize defines the intervals that a price/stopPrice can be increased/decreased by. # -1 because it doesn't return decimal point, pure exponential form self.tick_size = self.get_satoshi_count( float(filters['PRICE_FILTER']['tickSize'])) - 1 if self.quantity > 0: quantity = float(self.quantity) else: if self.max_amount: self.amount = float(Orders.get_balance("BTC")) lastBid, lastAsk = Orders.get_order_book(symbol) quantity = self.format_quantity(self.amount / lastBid) # Just for validation price = lastPrice notional = lastPrice * quantity # minQty = minimum order quantity if quantity < minQty: print self.log_wrap("Invalid quantity, minQty: %.8f (u: %.8f)" % (minQty, quantity)) valid = False if price < minPrice: print self.log_wrap("Invalid price, minPrice: %.8f (u: %.8f)" % (minPrice, price)) valid = False # minNotional = minimum order value (price * quantity) if notional < minNotional: print self.log_wrap( "Invalid notional, minNotional: %.8f (u: %.8f)" % (minNotional, notional)) valid = False if not valid: exit(1)
def setUp(self): self.timestamp = int(time.mktime(datetime.datetime.timetuple(datetime.datetime.now()))) self.order1 = Orders.create(order_id=self.timestamp, amount=1000) self.assertIsInstance(self.order1, Orders.Order) self.assertEqual(self.order1.status, "CREATED") #print tab(var_dump(self.order1, 1)) self.order2 = Orders.create(order_id=self.timestamp + 1, amount=1000)
def on_action(self, symbol): px = pd.DataFrame(Orders.get_candle_sticks(symbol, self.trading_period)) data = pd.DataFrame(Orders.get_candle_sticks( symbol, self.options.trading_period), dtype='float64') data.columns = self.column_names stock_data = StockDataFrame.retype(data) macd = stock_data['macd'] signal = stock_data['macds'] list_long_short = [ Advice.NAN ] # Since you need at least two days in the for loop has_crossed_up = False crossed_up_validations = 0 has_crossed_down = False crossed_down_validations = 0 for i in range(1, len(signal)): # If the MACD crosses the signal line upward macd_point = macd[i] signal_point = signal[i] macd_prev_point = macd[i - 1] signal_prev_point = signal[i - 1] if has_crossed_up: if self.placed_order() is False and macd_point > signal_point: crossed_up_validations += 1 if crossed_up_validations > self.options.macd_uv: list_long_short.append(Advice.BUY) has_crossed_up = False crossed_up_validations = 0 continue else: has_crossed_up = False crossed_up_validations = 0 list_long_short.append(Advice.HOLD) elif self.placed_order() and has_crossed_down: if macd_point < signal_point: crossed_down_validations += 1 if crossed_down_validations > self.options.macd_dv: list_long_short.append(Advice.SELL) has_crossed_down = False crossed_down_validations = 0 continue else: has_crossed_down = False crossed_down_validations = 0 list_long_short.append(Advice.HOLD) else: if macd_point > signal_point and macd_prev_point <= signal_prev_point: has_crossed_up = True # The other way around elif macd_point < signal_point and macd_prev_point >= signal_prev_point: has_crossed_down = True list_long_short.append(Advice.HOLD) px['Advice'] = list_long_short return px['Advice'][px['Advice'].size - 1]
def cancel(self, symbol, orderId): # If order is not filled, cancel it. check_order = Orders.get_order(symbol, orderId) if check_order[ 'status'] == 'NEW' or check_order['status'] != "CANCELLED": Orders.cancel_order(symbol, orderId) self.order_id = 0 self.order_data = None return True
def cancel(self, symbol, orderId): # If order is not filled, cancel it. check_order = Orders.get_order(symbol, orderId) if not check_order: self.order_id = 0 self.order_data = None return True if check_order['status'] == 'NEW' or check_order['status'] != 'CANCELLED': Orders.cancel_order(symbol, orderId) self.order_id = 0 self.order_data = None return True
def cancel(self, symbol, orderId): # If order is not filled, cancel it. check_order = Orders.get_order(symbol, orderId) if not check_order: self.order_id = 0 return True if check_order['status'] == 'NEW' or check_order[ 'status'] != "CANCELLED" or check_order[ 'status'] == 'PARTIALLY_FILLED': Orders.cancel_order(symbol, orderId) self.order_id = 0 return True
def action(self, symbol): # Order amount quantity = self.quantity # Fetches the ticker price ticker = Orders.get_ticker(symbol) while True: try: lastPrice = float(ticker['lastPrice']) except Exception, error: ticker = Orders.get_ticker(symbol) else: break
def run(self): self.orders = [] self.symbols = [] self.shares = {} with open(self.ordersFile, 'r') as fin: reader = csv.reader(fin) for row in reader: date = dt.datetime(int(row[0]), int(row[1]), int(row[2]), 16) symbol = row[3] action = row[4] quantity = float(row[5]) order = OrderWrapper(date, symbol, Orders.MarketOrder(action, quantity)) self.orders.append(order) if order.symbol not in self.symbols: self.symbols.append(order.symbol) self.shares[order.symbol] = 0 self.orders = sorted(self.orders, key=lambda order: order.date) startDate = self.orders[0].date endDate = self.orders[-1].date logger.debug("Needing %s", self.symbols) def doSimulate(df): self.df_data = df self.simulate() HistoricalData.requestMultiple(self.symbols, startDate, endDate, "ADJUSTED_LAST", "1 DAY", doSimulate)
def add_tab(self): tab1 = Products(self.notebook) tab2 = Customers(self.notebook) tab3 = Orders(self.notebook) self.notebook.add(tab1, text="Products") self.notebook.add(tab2, text="Customers") self.notebook.add(tab3, text="Orders")
def on_plot(self, symbol): df = pd.DataFrame(Orders.get_candle_sticks(symbol, self.options.trading_period), dtype='float64').fillna(0) df.columns = self.column_names stock_data = StockDataFrame.retype(df) window_ = stock_data['rsi_%d' % self.rsi_window] df['Sell Entry'] = window_ > self.options.rsi_cap df['Buy Entry'] = window_ < self.options.rsi_min # Create empty "Position" column df['Position'] = np.nan # Set position to -1 for sell signals df.loc[df['Sell Entry'], 'Position'] = -1 # Set position to -1 for buy signals df.loc[df['Buy Entry'], 'Position'] = 1 # Set starting position to flat (i.e. 0) df['Position'].iloc[0] = 0 # Forward fill the position column to show holding of positions through time df['Position'] = df['Position'].fillna(method='ffill') # Set up a column holding the daily Apple returns df['Market Returns'] = df['close'].pct_change() # Create column for Strategy Returns by multiplying the daily Apple returns by the position that was held at close # of business the previous day df['Strategy Returns'] = df['Market Returns'] * df['Position'].shift(1) # Finally plot the strategy returns versus Apple returns df[['Strategy Returns', 'Market Returns']].cumsum().plot(figsize=(20, 10)) plt.title('RSI(%d) Strategy Performance' % self.rsi_window) plt.show()
def buy(self, symbol, quantity, buyPrice): # Check last order self.checkorder() try: # Create order orderId = Orders.buy_limit(symbol, quantity, buyPrice) # Database log Database.write([ orderId, symbol, 0, buyPrice, 'BUY', quantity, self.option.profit ]) print self.log_wrap('Buy order created id:%d, q:%.8f, p:%.8f' % (orderId, quantity, float(buyPrice))) self.order_id = orderId self.bot_status = "buy" return orderId except Exception as e: print self.log_wrap('bl: %s' % (e)) # time.sleep(self.WAIT_TIME_BUY_SELL) WAIT_TIME_STOP_LOSS = 600 self.bot_status = "cancel" return None
def check_partial_order(self, symbol, orderId, price): #time.sleep(self.WAIT_TIME_BUY_SELL) self.partial_status = "hold" quantity = 0 while (self.partial_status == "hold"): order = Orders.get_order(symbol, orderId) if order['status'] == 'PARTIALLY_FILLED': print self.log_wrap("Order still partially filled...") quantity = self.format_quantity(float(order['executedQty'])) if self.min_notional > quantity * price: print self.log_wrap( "Can't sell below minimum allowable price. Hold for 10 seconds..." ) time.sleep(self.WAIT_TIME_CHECK_HOLD) else: self.cancel(symbol, orderId) self.partial_status = "partial" else: self.partial_status = "sell" quantity = self.format_quantity(float(order['executedQty'])) return quantity
def buy(self, symbol, quantity, buyPrice, profitableSellingPrice): # Do you have an open order? self.check_order() try: # Create order orderId = Orders.buy_limit(symbol, quantity, buyPrice) # Database log Database.write([ orderId, symbol, 0, buyPrice, 'BUY', quantity, self.option.profit ]) #print('Buy order created id:%d, q:%.8f, p:%.8f' % (orderId, quantity, float(buyPrice))) self.logger.info( '%s : Buy order created id:%d, q:%.8f, p:%.8f, Take profit aprox :%.8f' % (symbol, orderId, quantity, float(buyPrice), profitableSellingPrice)) self.order_id = orderId return orderId except Exception as e: #print('bl: %s' % (e)) self.logger.debug('Buy error: %s' % (e)) time.sleep(self.WAIT_TIME_BUY_SELL) return None
def buy(self, symbol, quantity, buyPrice, profitableSellingPrice): # Do you have an open order? self.check_order() try: # Create order orderId = Orders.buy_limit(symbol, quantity, buyPrice) # Database log Database.write([orderId, symbol, 0, buyPrice, 'BUY', quantity, self.option.profit]) #print('Buy order created id:%d, q:%.8f, p:%.8f' % (orderId, quantity, float(buyPrice))) self.logger.info('%s : Buy order created id:%d, q:%.8f, p:%.8f, Take profit aprox :%.8f' % (symbol, orderId, quantity, float(buyPrice), profitableSellingPrice)) self.order_id = orderId return orderId except Exception as e: #print('bl: %s' % (e)) self.logger.debug('Buy error: %s' % (e)) time.sleep(self.WAIT_TIME_BUY_SELL) return None
def stop(symbol, quantity, sell_id): # If the target is not reached, stop-loss. stop_order = Orders.get_order(symbol, sell_id) stopprice = self.calc(float(stop_order['price'])) lossprice = stopprice - (stopprice * self.stop_loss / 100) status = stop_order['status'] # Order status if status == 'NEW': if self.cancel(symbol, sell_id): # Stop loss if last_price <= lossprice: sello = Orders.sell_market(symbol, quantity) print('Stop-loss, sell market, %s' % (lossprice)) self.order_id = sello['orderId'] self.order_data = sello if sello == True: return True else: return False # Wait a while after the sale to the loss. time.sleep(self.WAIT_TIME_STOP_LOSS) else: return True elif status == 'FILLED': self.order_id = 0 self.order_data = "" print('Order filled') return True elif status == 'PARTIALLY_FILLED': print('Order partially filled') return True else: return False
def __init__(self): self.db = DB() self.__employees = Employees(self) self.__vendors = Vendors(self) self.__time_clock = TimeClock(self) self.__orders = Orders(self) self.__inventory = Inventory(self) self.__register = Register(self) self.account = Account()
def on_action(self, symbol): data = pd.DataFrame(Orders.get_candle_sticks( symbol, self.options.trading_period), dtype='float64') data.columns = self.column_names stock_data = StockDataFrame.retype(data) wpr = stock_data['wr_%d' % self.options.will_window] last_value = wpr[wpr.size - 1] validate = self.validate(wpr, last_value) return validate
def get_closes_minute(self, symbol, limit): start = (datetime.datetime.now() - datetime.timedelta(minutes=limit)).strftime("%s") * 1000 now = int(datetime.datetime.now().strftime("%s")) * 1000 sticks = Orders.get_candle_sticks_limit(symbol, self.trading_period, start, now) close_prices = list() for s in sticks: close_prices.append(s[4]) return close_prices
def __init__(self, env=Environment.BETA, host="localhost", port=8194): self.env = env self.host = host self.port = port self.notificationHandlers = [] self.requestMessageHandlers = {} self.subscriptionMessageHandlers = {} self.orderFields = [] self.routeFields = [] self.emsxServiceName = "" self.teams = None self.team = None self.initialize() self.orders = Orders(self) self.routes = Routes(self)
def on_action(self, symbol): data = pd.DataFrame(Orders.get_candle_sticks(symbol, self.options.trading_period), dtype='float64') data.columns = self.column_names stock_data = StockDataFrame.retype(data) window_ = stock_data['rsi_%d' % self.rsi_window] rsi = int(window_[window_.size - 1]) if self.placed_order() is False and rsi < self.options.rsi_min: return Advice.BUY if self.placed_order() and rsi > self.options.rsi_cap: return Advice.SELL return Advice.HOLD
def stop(self, symbol, quantity, orderId, sell_price): # If the target is not reached, stop-loss. stop_order = Orders.get_order(symbol, orderId) old_qty = quantity if float(stop_order['executedQty']) > 0: quantity = self.format_quantity(float(stop_order['executedQty'])) lossprice = sell_price - (sell_price * self.stop_loss / 100) status = stop_order['status'] # Order status if status == 'NEW': if self.cancel(symbol, orderId): # Stop loss lastBid, lastAsk = Orders.get_order_book(symbol) print self.log_wrap('Stop-loss, sell market, %s' % (lastAsk)) flago = 0 sub = quantity * 0.005 while (flago != 1): stop_order = Orders.get_order(symbol, orderId) status = stop_order['status'] if status == 'FILLED': return True flago = 1 break try: sell_id = Orders.sell_market(symbol, quantity)['orderId'] except Exception, error: quantity = self.format_quantity(float(quantity - sub)) else: flago = 1 sleep(1) else: print self.log_wrap( 'Cancel did not work... Might have been sold before stop loss...' ) self.total_sell = self.total_sell + 1 #Count sell return True
def validate(self): valid = True symbol = self.option.symbol filters = self.filters()['filters'] lastPrice = Orders.get_ticker(symbol) minQty = float(filters['LOT_SIZE']['minQty']) minPrice = float(filters['PRICE_FILTER']['minPrice']) minNotional = float(filters['MIN_NOTIONAL']['minNotional']) quantity = float(self.option.quantity) # stepSize defines the intervals that a quantity/icebergQty can be increased/decreased by. stepSize = float(filters['LOT_SIZE']['stepSize']) # tickSize defines the intervals that a price/stopPrice can be increased/decreased by tickSize = float(filters['PRICE_FILTER']['tickSize']) # Format quantity self.step_size = stepSize # If option increasing default tickSize greater than if (float(self.option.increasing) < tickSize): self.increasing = tickSize # If option decreasing default tickSize greater than if (float(self.option.decreasing) < tickSize): self.decreasing = tickSize # Just for validation price = lastPrice notional = lastPrice * quantity # minQty = minimum order quantity if quantity < minQty: print("Invalid quantity, minQty: %.8f (u: %.8f)" % (minQty, quantity)) valid = False if price < minPrice: print("Invalid price, minPrice: %.8f (u: %.8f)" % (minPrice, price)) valid = False # minNotional = minimum order value (price * quantity) if notional < minNotional: print("Invalid notional, minNotional: %.8f (u: %.8f)" % (minNotional, notional)) valid = False if not valid: exit(1)
def stop(self, symbol, quantity, orderId, sell_price): # If the target is not reached, stop-loss. stop_order = Orders.get_order(symbol, orderId) old_qty = quantity if float(stop_order['executedQty']) > 0: quantity = self.format_quantity(float(stop_order['executedQty'])) lossprice = sell_price - (sell_price * self.stop_loss / 100) status = stop_order['status'] # Order status if status == 'NEW': if self.cancel(symbol, orderId): # Stop loss lastBid, lastAsk = Orders.get_order_book(symbol) sello = Orders.sell_market(symbol, quantity) print(self.log_wrap('Stop-loss, sell market, %s' % (lastAsk))) flag2 = 0 while (flag2 != 1): try: sell_id = sello['orderId'] except Exception as error: sello = Orders.sell_market(symbol, quantity) else: flag2 = 1 break else: print( self.log_wrap( 'Cancel did not work... Might have been sold before stop loss...' )) return True elif status == 'PARTIALLY_FILLED': self.order_id = 0 print( self.log_wrap( 'Sell partially filled, hold sell position to prevent dust coin. Continue trading...' )) flag2 = 0 new_quantity = old_qty - quantity sello = Orders.sell_market(symbol, new_quantity) while (flag2 != 1): try: sell_id = sello['orderId'] except Exception as error: sello = Orders.sell_market(symbol, new_quantity) else: flag2 = 1 break time.sleep(self.WAIT_TIME_CHECK_SELL) return True elif status == 'FILLED': self.order_id = 0 print(self.log_wrap('Order filled before sell at loss!')) return True else: return False
def take_order(self, shopping_cart: ShoppingCart, shipping_type, cost: int, region_id: int): product_list = shopping_cart.checkout() if product_list.__len__() > 0: order = Orders(self._user_id) for item in product_list: data = ShoppingCart.get_item_details(item) product_id = data[0] quantity = data[3] order.add_order_detail(product_id, quantity) order.set_shipping_info(shipping_type, cost, region_id) order.place_order() else: print("product list is empty")
def filters(self): symbol = self.option.symbol # Get symbol exchange info symbol_info = Orders.get_info(symbol) if not symbol_info: print('Invalid symbol, please try again...') exit(1) symbol_info['filters'] = {item['filterType']: item for item in symbol_info['filters']} return symbol_info
def filters(self): symbol = self.option.symbol # Get symbol exchange info symbol_info = Orders.get_info(symbol) if not symbol_info: print( "Invalid trading pair symbol! Please verify launch parameters, and try again..." ) exit(1) symbol_info['filters'] = { item['filterType']: item for item in symbol_info['filters'] } return symbol_info
def test__orders(self): # Test for get_status status = Orders.get_status(order_id=self.timestamp) self.assertIsInstance(status, Orders.Order) self.assertEqual(float(status.order_id), self.timestamp) #print tab(var_dump(status, 1)) # Test for list order_list = Orders.list() self.assertIsNotNone(order_list) for order in order_list['list']: self.assertIsInstance(order, Orders.Order) #print tab(var_dump(order_list,2)) # Test for update updated_order = Orders.update(order_id=self.timestamp, amount=500) status = Orders.get_status(order_id=self.timestamp) self.assertEqual(status.amount, updated_order.amount) #print tab(var_dump(updated_order)) # Test for refund refunded_order = Orders.refund(unique_request_id=self.timestamp,order_id=1465833326,amount=10)
def display_orders(): ''' Function used to display the currently ongoing orders''' try: orders = Orders.load_orders() if ( len(orders) >= 1 ): print(" The current orders are: ") else: print("Currently there are no orders.") for index, placed_order in enumerate(orders, start=1): print(f"{index}. {placed_order}") input(READ_ENTER_KEY) except JSONDecodeError: input("Error on retrieving the orders\n")
def on_action(self, symbol): data = pd.DataFrame(Orders.get_candle_sticks(symbol, self.options.trading_period), dtype='float64').fillna(0) data.columns = self.column_names stock_data = StockDataFrame.retype(data) k_data = stock_data['kdjk_%d' % self.options.stoch_k] d_data = stock_data['kdjd_%d' % self.options.stoch_d] k_current = k_data[k_data.size - 1] d_current = d_data[d_data.size - 1] cross_downs = stock_data['kdjk_%d_xd_kdjd_%d' % (self.options.stoch_k, self.options.stoch_d)] cross_ups = stock_data['kdjk_%d_xu_kdjd_%d' % (self.options.stoch_k, self.options.stoch_d)] if cross_ups[cross_ups.size - 1] and self.placed_order() is False and k_current < self.options.stoch_min \ and Orders.has_enough_to_trade(symbol, self.options.quantity): if d_current < self.options.stoch_min: return Advice.STRONG_BUY else: return Advice.BUY if cross_downs[cross_downs.size - 1] and self.placed_order() and k_current > self.options.stoch_cap and \ Orders.has_enough_to_trade(symbol, buying=False, quantity=self.options.quantity): if d_current > self.options.stoch_cap: return Advice.STRONG_SELL else: return Advice.SELL return Advice.HOLD
def filters(self): symbol = self.option.symbol # Get symbol exchance info symbol_info = Orders.get_info(symbol) if not symbol_info: print ("Invalid symbol, please try again...") exit(1) symbol_info['filters'] = {item['filterType']: item for item in symbol_info['filters']} return symbol_info
def filters(self): symbol = self.option.symbol # Get symbol exchange info symbol_info = Orders.get_info(symbol) if not symbol_info: #print('Invalid symbol, please try again...') self.logger.error('Invalid symbol, please try again...') exit(1) symbol_info['filters'] = {item['filterType']: item for item in symbol_info['filters']} return symbol_info
def buy(self, symbol, quantity, buyPrice): # Do you have an open order? self.check_order() try: # Create order orderId = Orders.buy_limit(symbol, quantity, buyPrice) # Database log Database.write([orderId, symbol, 0, buyPrice, 'BUY', quantity, self.option.profit]) print('Buy order created id:%d, q:%.8f, p:%.8f' % (orderId, quantity, float(buyPrice))) self.order_id = orderId return orderId except Exception as e: print('bl: %s' % (e)) time.sleep(self.WAIT_TIME_BUY_SELL) return None
def validate(self): valid = True symbol = self.option.symbol filters = self.filters()['filters'] # Order book prices lastBid, lastAsk = Orders.get_order_book(symbol) lastPrice = Orders.get_ticker(symbol) minQty = float(filters['LOT_SIZE']['minQty']) minPrice = float(filters['PRICE_FILTER']['minPrice']) minNotional = float(filters['MIN_NOTIONAL']['minNotional']) quantity = float(self.option.quantity) # stepSize defines the intervals that a quantity/icebergQty can be increased/decreased by. stepSize = float(filters['LOT_SIZE']['stepSize']) # tickSize defines the intervals that a price/stopPrice can be increased/decreased by tickSize = float(filters['PRICE_FILTER']['tickSize']) # If option increasing default tickSize greater than if (float(self.option.increasing) < tickSize): self.increasing = tickSize # If option decreasing default tickSize greater than if (float(self.option.decreasing) < tickSize): self.decreasing = tickSize # Just for validation lastBid = lastBid + self.increasing # Set static # If quantity or amount is zero, minNotional increase 10% quantity = (minNotional / lastBid) quantity = quantity + (quantity * 10 / 100) notional = minNotional if self.amount > 0: # Calculate amount to quantity quantity = (self.amount / lastBid) if self.quantity > 0: # Format quantity step quantity = self.quantity quantity = self.format_step(quantity, stepSize) notional = lastBid * float(quantity) # Set Globals self.quantity = quantity self.step_size = stepSize # minQty = minimum order quantity if quantity < minQty: print('Invalid quantity, minQty: %.8f (u: %.8f)' % (minQty, quantity)) valid = False if lastPrice < minPrice: print('Invalid price, minPrice: %.8f (u: %.8f)' % (minPrice, lastPrice)) valid = False # minNotional = minimum order value (price * quantity) if notional < minNotional: print('Invalid notional, minNotional: %.8f (u: %.8f)' % (minNotional, notional)) valid = False if not valid: exit(1)
def action(self, symbol): # Order amount quantity = self.quantity # Fetches the ticker price lastPrice = Orders.get_ticker(symbol) # Order book prices lastBid, lastAsk = Orders.get_order_book(symbol) # Target buy price, add little increase #87 buyPrice = lastBid + self.increasing # Target sell price, decrease little sellPrice = lastAsk - self.decreasing # Spread ( profit ) profitableSellingPrice = self.calc(lastBid) # Check working mode if self.option.mode == 'range': buyPrice = float(self.option.buyprice) sellPrice = float(self.option.sellprice) profitableSellingPrice = sellPrice # Screen log if self.option.prints and self.order_id == 0: spreadPerc = (lastAsk/lastBid - 1) * 100.0 print('price:%.8f buyp:%.8f sellp:%.8f-bid:%.8f ask:%.8f spread:%.2f' % (lastPrice, buyPrice, profitableSellingPrice, lastBid, lastAsk, spreadPerc)) # analyze = threading.Thread(target=analyze, args=(symbol,)) # analyze.start() if self.order_id > 0: # Profit mode if self.order_data is not None: order = self.order_data; # Last control newProfitableSellingPrice = self.calc(float(order['price'])) if (lastAsk >= newProfitableSellingPrice): profitableSellingPrice = newProfitableSellingPrice # range mode if self.option.mode == 'range': profitableSellingPrice = self.option.sellprice ''' If the order is complete, try to sell it. ''' # Perform buy action sellAction = threading.Thread(target=self.sell, args=(symbol, quantity, self.order_id, profitableSellingPrice, lastPrice,)) sellAction.start() return ''' Did profit get caught if ask price is greater than profit price, buy with my buy price, ''' if (lastAsk >= profitableSellingPrice and self.option.mode == 'profit') or \ (lastPrice <= float(self.option.buyprice) and self.option.mode == 'range'): if self.order_id == 0: self.buy(symbol, quantity, buyPrice)
def sell(self, symbol, quantity, orderId, sell_price, last_price): ''' The specified limit will try to sell until it reaches. If not successful, the order will be canceled. ''' buy_order = Orders.get_order(symbol, orderId) if buy_order['status'] == 'FILLED' and buy_order['side'] == 'BUY': print('Buy order filled... Try sell...') else: time.sleep(self.WAIT_TIME_CHECK_BUY_SELL) if buy_order['status'] == 'FILLED' and buy_order['side'] == 'BUY': print('Buy order filled after 0.1 second... Try sell...') elif buy_order['status'] == 'PARTIALLY_FILLED' and buy_order['side'] == 'BUY': print('Buy order partially filled... Try sell... Cancel remaining buy...') self.cancel(symbol, orderId) else: self.cancel(symbol, orderId) print('Buy order fail (Not filled) Cancel order...') self.order_id = 0 return sell_order = Orders.sell_limit(symbol, quantity, sell_price) sell_id = sell_order['orderId'] print('Sell order create id: %d' % sell_id) time.sleep(self.WAIT_TIME_CHECK_SELL) if sell_order['status'] == 'FILLED': print('Sell order (Filled) Id: %d' % sell_id) print('LastPrice : %.8f' % last_price) print('Profit: %%%s. Buy price: %.8f Sell price: %.8f' % (self.option.profit, float(sell_order['price']), sell_price)) self.order_id = 0 self.order_data = None return ''' If all sales trials fail, the grievance is stop-loss. ''' if self.stop_loss > 0: # If sell order failed after 5 seconds, 5 seconds more wait time before selling at loss time.sleep(self.WAIT_TIME_CHECK_SELL) if self.stop(symbol, quantity, sell_id, last_price): if Orders.get_order(symbol, sell_id)['status'] != 'FILLED': print('We apologize... Sold at loss...') else: print('We apologize... Cant sell even at loss... Please sell manually... Stopping program...') self.cancel(symbol, sell_id) exit(1) while (sell_status != 'FILLED'): time.sleep(self.WAIT_TIME_CHECK_SELL) sell_status = Orders.get_order(symbol, sell_id)['status'] lastPrice = Orders.get_ticker(symbol) print('Status: %s Current price: %.8f Sell price: %.8f' % (sell_status, lastPrice, sell_price)) print('Sold! Continue trading...') self.order_id = 0 self.order_data = None