def orders_change_thread(): orders = {} pushover = Pushover() while True: completed = "" pending = "" new = "" new_orders = exchange.get_open_orders() balance = exchange.get_balance() if orders != new_orders: for coin in orders: for o in orders[coin]: if coin not in new_orders: completed += "{0} {1} amount: {2}, total: {3}\n".format(o['type'].capitalize(), coin, o['amount'], o['total']) else: for new_o in new_orders[coin]: if new_o != o: completed += "{0} {1} amount: {2}, total: {3}\n".format(o['type'].capitalize(), coin, o['amount'], o['total']) for coin in new_orders: for o in new_orders[coin]: if coin not in orders: new += "{0} {1} amount: {2}, total: {3}\n".format(o['type'].capitalize(), coin, o['amount'], o['total']) else: for old_o in orders[coin]: if old_o != o: new += "{0} {1} amount: {2}, total: {3}\n".format(o['type'].capitalize(), coin, o['amount'], o['total']) for coin in new_orders: for o in new_orders[coin]: pending += "{0} {1} amount: {2}, total: {3}\n".format(o['type'].capitalize(), coin, o['amount'], o['total']) message = "" if completed != "": message += "Completed or canceled orders:\n" message += completed message += "\n" if new != "": message += "New orders:\n" message += new message += "\n" if pending != "": message += "Pending orders:\n" message += pending message += "\n" if message != "": message += "Total balance: {0:.2f} USDT".format(sum([coin['usdtValue'] for coin in balance])) print("---------------------------") print(datetime.datetime.now()) print(message) pushover.send(message) orders = new_orders time.sleep(10)
def _status(bot: Bot, update: Update) -> None: """ Handler for /status. Returns the current TradeThread status :param bot: telegram bot :param update: message update :return: None """ # Fetch open trade trades = Trade.query.filter(Trade.is_open.is_(True)).all() if get_state() != State.RUNNING: send_msg('*Status:* `trader is not running`', bot=bot) elif not trades: send_msg('*Status:* `no active order`', bot=bot) else: for trade in trades: # calculate profit and send message to user current_rate = exchange.get_ticker(trade.pair)['bid'] current_profit = 100 * ( (current_rate - trade.open_rate) / trade.open_rate) orders = exchange.get_open_orders(trade.pair) orders = [o for o in orders if o['id'] == trade.open_order_id] order = orders[0] if orders else None fmt_close_profit = '{:.2f}%'.format(round( trade.close_profit, 2)) if trade.close_profit else None message = """ *Trade ID:* `{trade_id}` *Current Pair:* [{pair}]({market_url}) *Open Since:* `{date}` *Amount:* `{amount}` *Open Rate:* `{open_rate}` *Close Rate:* `{close_rate}` *Current Rate:* `{current_rate}` *Close Profit:* `{close_profit}` *Current Profit:* `{current_profit:.2f}%` *Open Order:* `{open_order}` """.format( trade_id=trade.id, pair=trade.pair, market_url=exchange.get_pair_detail_url(trade.pair), date=arrow.get(trade.open_date).humanize(), open_rate=trade.open_rate, close_rate=trade.close_rate, current_rate=current_rate, amount=round(trade.amount, 8), close_profit=fmt_close_profit, current_profit=round(current_profit, 2), open_order='{} ({})'.format(order['remaining'], order['type']) if order else None, ) send_msg(message, bot=bot)
def process_sell(trades): for trade in trades: # Check if there is already an open order for this trade orders = exchange.get_open_orders(trade.pair) orders = [o for o in orders if o['id'] == trade.open_order_id] if orders: logger.info('There is an open order for: %s', orders[0]) else: # Update state trade.open_order_id = None # Check if this trade can be closed if not close_trade_if_fulfilled(trade): # Check if we can sell our current pair handle_trade(trade)
def _process() -> None: """ Queries the persistence layer for open trades and handles them, otherwise a new trade is created. :return: None """ try: # Query trades from persistence layer trades = Trade.query.filter(Trade.is_open.is_(True)).all() # TODO Add BTC Current < Open # p_buy = Process(target=process_buy, args=[trades]) # p_buy.start() # p_sell = Process(target=process_sell, args=[trades]) # p_sell.start() # p_buy.join() # p_sell.join() if len(trades) < _CONF['max_open_trades']: try: # Create entity and execute trade trade = create_trade(float(_CONF['stake_amount']), exchange.EXCHANGE) if trade: Trade.session.add(trade) else: logging.info('Streets askin too high...') except ValueError: logger.exception('Unable to create trade') for trade in trades: # Check if there is already an open order for this trade orders = exchange.get_open_orders(trade.pair) orders = [o for o in orders if o['id'] == trade.open_order_id] if orders: logger.info('There is an open order for: %s', orders[0]) else: # Update state trade.open_order_id = None # Check if this trade can be closed if not close_trade_if_fulfilled(trade): # Check if we can sell our current pair handle_trade(trade) Trade.session.flush() except (ConnectionError, json.JSONDecodeError) as error: msg = 'Got {} in _process()'.format(error.__class__.__name__) logger.exception(msg)
def get_status(self, trades): messages = [] for trade in trades: # calculate profit and send message to user current_rate = exchange.get_ticker(trade.pair)['bid'] current_profit = 100 * ( (current_rate - trade.open_rate) / trade.open_rate) orders = exchange.get_open_orders(trade.pair) orders = [o for o in orders if o['id'] == trade.open_order_id] order = orders[0] if orders else None fmt_close_profit = '{:.2f}%'.format(round( trade.close_profit, 2)) if trade.close_profit else None markdown_msg = """ *Trade ID:* `{trade_id}` *Current Pair:* [{pair}]({market_url}) *Open Since:* `{date}` *Amount:* `{amount}` *Open Rate:* `{open_rate}` *Close Rate:* `{close_rate}` *Current Rate:* `{current_rate}` *Close Profit:* `{close_profit}` *Current Profit:* `{current_profit:.2f}%` *Open Order:* `{open_order}` """.format( trade_id=trade.id, pair=trade.pair, market_url=exchange.get_pair_detail_url(trade.pair), date=arrow.get(trade.open_date).humanize(), open_rate=trade.open_rate, close_rate=trade.close_rate, current_rate=current_rate, amount=round(trade.amount, 8), close_profit=fmt_close_profit, current_profit=round(current_profit, 2), open_order='{} ({})'.format(order['remaining'], order['type']) if order else None, ) messages.append(markdown_msg) return messages
def orders_change_thread(): orders = {} pushover = Pushover() while True: completed = "" pending = "" new = "" new_orders = exchange.get_open_orders() balance = exchange.get_balance() if orders != new_orders: for coin in orders: for o in orders[coin]: if coin not in new_orders: completed += "{0} {1} amount: {2}, total: {3}\n".format( o['type'].capitalize(), coin, o['amount'], o['total']) else: for new_o in new_orders[coin]: if new_o != o: completed += "{0} {1} amount: {2}, total: {3}\n".format( o['type'].capitalize(), coin, o['amount'], o['total']) for coin in new_orders: for o in new_orders[coin]: if coin not in orders: new += "{0} {1} amount: {2}, total: {3}\n".format( o['type'].capitalize(), coin, o['amount'], o['total']) else: for old_o in orders[coin]: if old_o != o: new += "{0} {1} amount: {2}, total: {3}\n".format( o['type'].capitalize(), coin, o['amount'], o['total']) for coin in new_orders: for o in new_orders[coin]: pending += "{0} {1} amount: {2}, total: {3}\n".format( o['type'].capitalize(), coin, o['amount'], o['total']) message = "" if completed != "": message += "Completed or canceled orders:\n" message += completed message += "\n" if new != "": message += "New orders:\n" message += new message += "\n" if pending != "": message += "Pending orders:\n" message += pending message += "\n" if message != "": message += "Total balance: {0:.2f} USDT".format( sum([coin['usdtValue'] for coin in balance])) print("---------------------------") print(datetime.datetime.now()) print(message) pushover.send(message) orders = new_orders time.sleep(10)