mirror of
https://github.com/freqtrade/freqtrade.git
synced 2024-11-10 10:21:59 +00:00
commit
c7b6e19872
|
@ -282,104 +282,95 @@ class Exchange(object):
|
|||
price = ceil(big_price) / pow(10, symbol_prec)
|
||||
return price
|
||||
|
||||
def buy(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force) -> Dict:
|
||||
if self._conf['dry_run']:
|
||||
order_id = f'dry_run_buy_{randint(0, 10**6)}'
|
||||
self._dry_run_open_orders[order_id] = {
|
||||
def dry_run_order(self, pair: str, ordertype: str, side: str, amount: float,
|
||||
rate: float, params: Dict = {}) -> Dict[str, Any]:
|
||||
order_id = f'dry_run_{side}_{randint(0, 10**6)}'
|
||||
dry_order = { # TODO: additional entry should be added for stoploss limit
|
||||
"id": order_id,
|
||||
'pair': pair,
|
||||
'price': rate,
|
||||
'amount': amount,
|
||||
"cost": amount * rate,
|
||||
'type': ordertype,
|
||||
'side': 'buy',
|
||||
'remaining': 0.0,
|
||||
'remaining': amount,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': 'closed',
|
||||
'fee': None
|
||||
'status': "open",
|
||||
'fee': None,
|
||||
"info": {}
|
||||
}
|
||||
return {'id': order_id}
|
||||
self._store_dry_order(dry_order)
|
||||
return dry_order
|
||||
|
||||
def _store_dry_order(self, dry_order: Dict) -> None:
|
||||
closed_order = dry_order.copy()
|
||||
if closed_order["type"] in ["market", "limit"]:
|
||||
closed_order.update({
|
||||
"status": "closed",
|
||||
"filled": closed_order["amount"],
|
||||
"remaining": 0
|
||||
})
|
||||
self._dry_run_open_orders[closed_order["id"]] = closed_order
|
||||
|
||||
def create_order(self, pair: str, ordertype: str, side: str, amount: float,
|
||||
rate: float, params: Dict = {}) -> Dict:
|
||||
try:
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
rate = self.symbol_price_prec(pair, rate) if ordertype != 'market' else None
|
||||
|
||||
params = self._params.copy()
|
||||
if time_in_force != 'gtc':
|
||||
params.update({'timeInForce': time_in_force})
|
||||
|
||||
return self._api.create_order(pair, ordertype, 'buy',
|
||||
return self._api.create_order(pair, ordertype, side,
|
||||
amount, rate, params)
|
||||
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to create limit buy order on market {pair}.'
|
||||
f'Tried to buy amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Insufficient funds to create {ordertype} {side} order on market {pair}.'
|
||||
f'Tried to {side} amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not create limit buy order on market {pair}.'
|
||||
f'Tried to buy amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Could not create {ordertype} {side} order on market {pair}.'
|
||||
f'Tried to {side} amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place buy order due to {e.__class__.__name__}. Message: {e}')
|
||||
f'Could not place {side} order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
def buy(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force) -> Dict:
|
||||
|
||||
if self._conf['dry_run']:
|
||||
dry_order = self.dry_run_order(pair, ordertype, "buy", amount, rate)
|
||||
return dry_order
|
||||
|
||||
params = self._params.copy()
|
||||
if time_in_force != 'gtc':
|
||||
params.update({'timeInForce': time_in_force})
|
||||
|
||||
return self.create_order(pair, ordertype, 'buy', amount, rate, params)
|
||||
|
||||
def sell(self, pair: str, ordertype: str, amount: float,
|
||||
rate: float, time_in_force='gtc') -> Dict:
|
||||
if self._conf['dry_run']:
|
||||
order_id = f'dry_run_sell_{randint(0, 10**6)}'
|
||||
self._dry_run_open_orders[order_id] = {
|
||||
'pair': pair,
|
||||
'price': rate,
|
||||
'amount': amount,
|
||||
'type': ordertype,
|
||||
'side': 'sell',
|
||||
'remaining': 0.0,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': 'closed'
|
||||
}
|
||||
return {'id': order_id}
|
||||
|
||||
try:
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
rate = self.symbol_price_prec(pair, rate) if ordertype != 'market' else None
|
||||
if self._conf['dry_run']:
|
||||
dry_order = self.dry_run_order(pair, ordertype, "sell", amount, rate)
|
||||
return dry_order
|
||||
|
||||
params = self._params.copy()
|
||||
if time_in_force != 'gtc':
|
||||
params.update({'timeInForce': time_in_force})
|
||||
|
||||
return self._api.create_order(pair, ordertype, 'sell',
|
||||
amount, rate, params)
|
||||
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to create limit sell order on market {pair}.'
|
||||
f'Tried to sell amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not create limit sell order on market {pair}.'
|
||||
f'Tried to sell amount {amount} at rate {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place sell order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
return self.create_order(pair, ordertype, 'sell', amount, rate, params)
|
||||
|
||||
def stoploss_limit(self, pair: str, amount: float, stop_price: float, rate: float) -> Dict:
|
||||
"""
|
||||
creates a stoploss limit order.
|
||||
NOTICE: it is not supported by all exchanges. only binance is tested for now.
|
||||
"""
|
||||
ordertype = "stop_loss_limit"
|
||||
|
||||
# Set the precision for amount and price(rate) as accepted by the exchange
|
||||
amount = self.symbol_amount_prec(pair, amount)
|
||||
rate = self.symbol_price_prec(pair, rate)
|
||||
stop_price = self.symbol_price_prec(pair, stop_price)
|
||||
|
||||
# Ensure rate is less than stop price
|
||||
|
@ -388,51 +379,18 @@ class Exchange(object):
|
|||
'In stoploss limit order, stop price should be more than limit price')
|
||||
|
||||
if self._conf['dry_run']:
|
||||
order_id = f'dry_run_buy_{randint(0, 10**6)}'
|
||||
self._dry_run_open_orders[order_id] = {
|
||||
'info': {},
|
||||
'id': order_id,
|
||||
'pair': pair,
|
||||
'price': stop_price,
|
||||
'amount': amount,
|
||||
'type': 'stop_loss_limit',
|
||||
'side': 'sell',
|
||||
'remaining': amount,
|
||||
'datetime': arrow.utcnow().isoformat(),
|
||||
'status': 'open',
|
||||
'fee': None
|
||||
}
|
||||
return self._dry_run_open_orders[order_id]
|
||||
|
||||
try:
|
||||
dry_order = self.dry_run_order(
|
||||
pair, ordertype, "sell", amount, stop_price)
|
||||
return dry_order
|
||||
|
||||
params = self._params.copy()
|
||||
params.update({'stopPrice': stop_price})
|
||||
|
||||
order = self._api.create_order(pair, 'stop_loss_limit', 'sell',
|
||||
amount, rate, params)
|
||||
order = self.create_order(pair, ordertype, 'sell', amount, rate, params)
|
||||
logger.info('stoploss limit order added for %s. '
|
||||
'stop price: %s. limit: %s' % (pair, stop_price, rate))
|
||||
return order
|
||||
|
||||
except ccxt.InsufficientFunds as e:
|
||||
raise DependencyException(
|
||||
f'Insufficient funds to place stoploss limit order on market {pair}. '
|
||||
f'Tried to put a stoploss amount {amount} with '
|
||||
f'stop {stop_price} and limit {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except ccxt.InvalidOrder as e:
|
||||
raise DependencyException(
|
||||
f'Could not place stoploss limit order on market {pair}.'
|
||||
f'Tried to place stoploss amount {amount} with '
|
||||
f'stop {stop_price} and limit {rate} (total {rate*amount}).'
|
||||
f'Message: {e}')
|
||||
except (ccxt.NetworkError, ccxt.ExchangeError) as e:
|
||||
raise TemporaryError(
|
||||
f'Could not place stoploss limit order due to {e.__class__.__name__}. Message: {e}')
|
||||
except ccxt.BaseError as e:
|
||||
raise OperationalException(e)
|
||||
|
||||
@retrier
|
||||
def get_balance(self, currency: str) -> float:
|
||||
if self._conf['dry_run']:
|
||||
|
@ -637,9 +595,6 @@ class Exchange(object):
|
|||
def get_order(self, order_id: str, pair: str) -> Dict:
|
||||
if self._conf['dry_run']:
|
||||
order = self._dry_run_open_orders[order_id]
|
||||
order.update({
|
||||
'id': order_id
|
||||
})
|
||||
return order
|
||||
try:
|
||||
return self._api.fetch_order(order_id, pair)
|
||||
|
|
|
@ -443,6 +443,56 @@ def test_exchange_has(default_conf, mocker):
|
|||
assert not exchange.exchange_has("deadbeef")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("side", [
|
||||
("buy"),
|
||||
("sell")
|
||||
])
|
||||
def test_dry_run_order(default_conf, mocker, side):
|
||||
default_conf['dry_run'] = True
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
|
||||
order = exchange.dry_run_order(
|
||||
pair='ETH/BTC', ordertype='limit', side=side, amount=1, rate=200)
|
||||
assert 'id' in order
|
||||
assert f'dry_run_{side}_' in order["id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("side", [
|
||||
("buy"),
|
||||
("sell")
|
||||
])
|
||||
@pytest.mark.parametrize("ordertype,rate", [
|
||||
("market", None),
|
||||
("limit", 200),
|
||||
("stop_loss_limit", 200)
|
||||
])
|
||||
def test_create_order(default_conf, mocker, side, ordertype, rate):
|
||||
api_mock = MagicMock()
|
||||
order_id = 'test_prod_{}_{}'.format(side, randint(0, 10 ** 6))
|
||||
api_mock.create_order = MagicMock(return_value={
|
||||
'id': order_id,
|
||||
'info': {
|
||||
'foo': 'bar'
|
||||
}
|
||||
})
|
||||
default_conf['dry_run'] = False
|
||||
mocker.patch('freqtrade.exchange.Exchange.symbol_amount_prec', lambda s, x, y: y)
|
||||
mocker.patch('freqtrade.exchange.Exchange.symbol_price_prec', lambda s, x, y: y)
|
||||
exchange = get_patched_exchange(mocker, default_conf, api_mock)
|
||||
|
||||
order = exchange.create_order(
|
||||
pair='ETH/BTC', ordertype=ordertype, side=side, amount=1, rate=200)
|
||||
|
||||
assert 'id' in order
|
||||
assert 'info' in order
|
||||
assert order['id'] == order_id
|
||||
assert api_mock.create_order.call_args[0][0] == 'ETH/BTC'
|
||||
assert api_mock.create_order.call_args[0][1] == ordertype
|
||||
assert api_mock.create_order.call_args[0][2] == side
|
||||
assert api_mock.create_order.call_args[0][3] == 1
|
||||
assert api_mock.create_order.call_args[0][4] is rate
|
||||
|
||||
|
||||
def test_buy_dry_run(default_conf, mocker):
|
||||
default_conf['dry_run'] = True
|
||||
exchange = get_patched_exchange(mocker, default_conf)
|
||||
|
|
Loading…
Reference in New Issue
Block a user