implement support for concurrent open trades

This commit is contained in:
gcarq 2017-05-17 19:42:45 +02:00
parent 3fa8aae66d
commit d572b7bdbe
3 changed files with 63 additions and 49 deletions

60
main.py
View File

@ -24,7 +24,6 @@ __license__ = "custom"
__version__ = "0.5.1" __version__ = "0.5.1"
conf = get_conf() conf = get_conf()
api_wrapper = get_exchange_api(conf) api_wrapper = get_exchange_api(conf)
@ -79,33 +78,35 @@ class TradeThread(threading.Thread):
:return: None :return: None
""" """
# Query trades from persistence layer # Query trades from persistence layer
trade = Trade.query.filter(Trade.is_open.is_(True)).first() trades = Trade.query.filter(Trade.is_open.is_(True)).all()
if not trade: if len(trades) < conf['max_open_trades']:
# Create entity and execute trade # Create entity and execute trade
Session.add(create_trade(float(conf['stake_amount']), api_wrapper.exchange)) try:
return Session.add(create_trade(float(conf['stake_amount']), api_wrapper.exchange))
except ValueError:
logger.exception('ValueError during trade creation')
for trade in trades:
# Check if there is already an open order for this trade
orders = api_wrapper.get_open_orders(trade.pair)
orders = [o for o in orders if o['id'] == trade.open_order_id]
if orders:
msg = 'There exists an open order for this trade: (total: {}, remaining: {}, type: {}, id: {})' \
.format(round(orders[0]['amount'], 8),
round(orders[0]['remaining'], 8),
orders[0]['type'],
orders[0]['id'])
logger.info(msg)
continue
# Check if there is already an open order for this trade # Update state
orders = api_wrapper.get_open_orders(trade.pair) trade.open_order_id = None
orders = [o for o in orders if o['id'] == trade.open_order_id] # Check if this trade can be marked as closed
if orders: if close_trade_if_fulfilled(trade):
msg = 'There exists an open order for this trade: (total: {}, remaining: {}, type: {}, id: {})' \ logger.info('No open orders found and trade is fulfilled. Marking as closed ...')
.format(round(orders[0]['amount'], 8), continue
round(orders[0]['remaining'], 8),
orders[0]['type'],
orders[0]['id'])
logger.info(msg)
return
# Update state # Check if we can sell our current pair
trade.open_order_id = None handle_trade(trade)
# Check if this trade can be marked as closed
if close_trade_if_fulfilled(trade):
logger.info('No open orders found and trade is fulfilled. Marking as closed ...')
return
# Check if we can sell our current pair
handle_trade(trade)
# Initial stopped TradeThread instance # Initial stopped TradeThread instance
_instance = TradeThread() _instance = TradeThread()
@ -178,16 +179,21 @@ def create_trade(stake_amount: float, exchange):
:param stake_amount: amount of btc to spend :param stake_amount: amount of btc to spend
:param exchange: exchange to use :param exchange: exchange to use
""" """
logger.info('Creating new trade with stake_amount: {} ...'.format(stake_amount))
whitelist = conf[exchange.name.lower()]['pair_whitelist'] whitelist = conf[exchange.name.lower()]['pair_whitelist']
# Check if btc_amount is fulfilled # Check if btc_amount is fulfilled
if api_wrapper.get_balance('BTC') < stake_amount: if api_wrapper.get_balance('BTC') < stake_amount:
raise ValueError('BTC amount is not fulfilled') raise ValueError('BTC amount is not fulfilled')
# Remove latest trade pair from whitelist # Remove currently opened and latest pairs from whitelist
latest_trade = Trade.query.order_by(Trade.id.desc()).first() latest_trade = Trade.query.filter(Trade.is_open.is_(False)).order_by(Trade.id.desc()).first()
open_trades = Trade.query.filter(Trade.is_open.is_(True)).all()
if latest_trade and latest_trade.pair in whitelist: if latest_trade and latest_trade.pair in whitelist:
whitelist.remove(latest_trade.pair) whitelist.remove(latest_trade.pair)
logger.debug('Ignoring {} in pair whitelist'.format(latest_trade.pair)) logger.debug('Ignoring {} in pair whitelist'.format(latest_trade.pair))
for trade in open_trades:
whitelist.remove(trade.pair)
logger.debug('Ignoring {} in pair whitelist'.format(trade.pair))
if not whitelist: if not whitelist:
raise ValueError('No pair in whitelist') raise ValueError('No pair in whitelist')

View File

@ -54,19 +54,21 @@ class TelegramHandler(object):
:return: None :return: None
""" """
# Fetch open trade # Fetch open trade
trade = Trade.query.filter(Trade.is_open.is_(True)).first() trades = Trade.query.filter(Trade.is_open.is_(True)).all()
from main import get_instance from main import get_instance
if not get_instance().is_alive(): if not get_instance().is_alive():
message = '*Status:* `trader stopped`' TelegramHandler.send_msg('*Status:* `trader stopped`', bot=bot)
elif not trade: elif not trades:
message = '*Status:* `no active order`' TelegramHandler.send_msg('*Status:* `no active order`', bot=bot)
else: else:
# calculate profit and send message to user for trade in trades:
current_rate = api_wrapper.get_ticker(trade.pair)['bid'] # calculate profit and send message to user
current_profit = 100 * ((current_rate - trade.open_rate) / trade.open_rate) current_rate = api_wrapper.get_ticker(trade.pair)['bid']
open_orders = api_wrapper.get_open_orders(trade.pair) current_profit = 100 * ((current_rate - trade.open_rate) / trade.open_rate)
order = open_orders[0] if open_orders else None orders = api_wrapper.get_open_orders(trade.pair)
message = """ orders = [o for o in orders if o['id'] == trade.open_order_id]
order = orders[0] if orders else None
message = """
*Current Pair:* [{pair}](https://bittrex.com/Market/Index?MarketName={pair}) *Current Pair:* [{pair}](https://bittrex.com/Market/Index?MarketName={pair})
*Open Since:* `{date}` *Open Since:* `{date}`
*Amount:* `{amount}` *Amount:* `{amount}`
@ -76,18 +78,18 @@ class TelegramHandler(object):
*Close Profit:* `{close_profit}` *Close Profit:* `{close_profit}`
*Current Profit:* `{current_profit}%` *Current Profit:* `{current_profit}%`
*Open Order:* `{open_order}` *Open Order:* `{open_order}`
""".format( """.format(
pair=trade.pair.replace('_', '-'), pair=trade.pair.replace('_', '-'),
date=arrow.get(trade.open_date).humanize(), date=arrow.get(trade.open_date).humanize(),
open_rate=trade.open_rate, open_rate=trade.open_rate,
close_rate=trade.close_rate, close_rate=trade.close_rate,
current_rate=current_rate, current_rate=current_rate,
amount=round(trade.amount, 8), amount=round(trade.amount, 8),
close_profit='{}%'.format(round(trade.close_profit, 2)) if trade.close_profit else None, close_profit='{}%'.format(round(trade.close_profit, 2)) if trade.close_profit else None,
current_profit=round(current_profit, 2), current_profit=round(current_profit, 2),
open_order='{} ({})'.format(order['remaining'], order['type']) if order else None, open_order='{} ({})'.format(order['remaining'], order['type']) if order else None,
) )
TelegramHandler.send_msg(message, bot=bot) TelegramHandler.send_msg(message, bot=bot)
@staticmethod @staticmethod
@authorized_only @authorized_only
@ -167,6 +169,10 @@ class TelegramHandler(object):
:param update: message update :param update: message update
:return: None :return: None
""" """
# TODO: make compatible with max_open_orders
TelegramHandler.send_msg('`Currently not implemented`')
return
trade = Trade.query.filter(Trade.is_open.is_(True)).first() trade = Trade.query.filter(Trade.is_open.is_(True)).first()
if not trade: if not trade:
TelegramHandler.send_msg('`There is no open trade`') TelegramHandler.send_msg('`There is no open trade`')

View File

@ -28,6 +28,8 @@ def validate_conf(conf):
:param conf: config as dict :param conf: config as dict
:return: None, raises ValueError if something is wrong :return: None, raises ValueError if something is wrong
""" """
if not isinstance(conf.get('max_open_trades'), int):
raise ValueError('max_open_trades must be a int')
if not isinstance(conf.get('stake_amount'), float): if not isinstance(conf.get('stake_amount'), float):
raise ValueError('stake_amount must be a float') raise ValueError('stake_amount must be a float')
if not isinstance(conf.get('dry_run'), bool): if not isinstance(conf.get('dry_run'), bool):