Coverage for django_napse/core/models/orders/managers/order.py: 75%

24 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-03-12 13:49 +0000

1from django.apps import apps 

2from django.db import models 

3 

4from django_napse.utils.constants import EXCHANGE_PAIRS, ORDER_LEEWAY_PERCENTAGE, SIDES, TRANSACTION_TYPES 

5from django_napse.utils.errors import OrderError 

6 

7 

8class OrderManager(models.Manager): 

9 def create( 

10 self, 

11 batch, 

12 connection, 

13 asked_for_amount: float, 

14 asked_for_ticker: str, 

15 pair: str, 

16 price: float, 

17 side: str, 

18 ): 

19 if side not in [SIDES.BUY, SIDES.SELL, SIDES.KEEP]: 

20 error_msg = f"Side {side} is not valid." 

21 raise OrderError.InvalidOrder(error_msg) 

22 

23 if side == SIDES.BUY and asked_for_ticker != batch.controller.quote: 

24 error_msg = f"Ticker {asked_for_ticker} is not valid for a buy order. Should be {batch.controller.quote}." 

25 raise OrderError.InvalidOrder(error_msg) 

26 

27 if side == SIDES.SELL and asked_for_ticker != batch.controller.base: 

28 error_msg = f"Ticker {asked_for_ticker} is not valid for a sell order. Should be {batch.controller.base}." 

29 raise OrderError.InvalidOrder(error_msg) 

30 

31 # if side == SIDES.KEEP: 

32 # return None 

33 

34 order = self.model( 

35 batch=batch, 

36 connection=connection, 

37 asked_for_amount=asked_for_amount, 

38 pair=pair, 

39 price=price, 

40 side=side, 

41 asked_for_ticker=asked_for_ticker, 

42 ) 

43 order.save() 

44 

45 OrderWallet = apps.get_model("django_napse_core", "OrderWallet") 

46 wallet = OrderWallet.objects.create(title=f"Wallet for order {order.pk}", owner=order) 

47 

48 Transaction = apps.get_model("django_napse_core", "Transaction") 

49 Transaction.objects.create( 

50 from_wallet=connection.wallet, 

51 to_wallet=wallet, 

52 amount=asked_for_amount * (1 + ORDER_LEEWAY_PERCENTAGE / 100), 

53 ticker=EXCHANGE_PAIRS[connection.space.exchange_account.exchange.name][pair]["base" if side == SIDES.SELL else "quote"], 

54 transaction_type=TRANSACTION_TYPES.ORDER_DEPOSIT, 

55 ) 

56 order.debited_amount = asked_for_amount * (1 + ORDER_LEEWAY_PERCENTAGE / 100) 

57 order.save() 

58 return order