Coverage for django_napse/api/orders/serializers/order_serializer.py: 58%
26 statements
« prev ^ index » next coverage.py v7.4.3, created at 2024-03-12 13:49 +0000
« prev ^ index » next coverage.py v7.4.3, created at 2024-03-12 13:49 +0000
1from rest_framework import serializers
3from django_napse.core.models import Order
4from django_napse.utils.constants import SIDES
7class OrderSerializer(serializers.ModelSerializer):
8 """.
10 {
11 "side": "BUY",
12 "completed": true,
13 "spent": {
14 "ticker": "BTC",
15 "amount": 0.1,
16 "price": 1,
17 "value": 0.1,
18 },
19 "received": {
20 "ticker": "MATIC",
21 "amount": 995,
22 "price": 0.0001,
23 "value": 0.095,
24 },
25 "fees": {
26 "ticker": "BTC",
27 "amount": 5,
28 "price": 0.0001,
29 "value": 0.05,
30 },
31 "created_at": "2021-09-01T12:00:00Z",
32 }
33 """
35 spent = serializers.SerializerMethodField()
36 received = serializers.SerializerMethodField()
37 fees = serializers.SerializerMethodField()
39 class Meta:
40 model = Order
41 fields = [
42 "side",
43 "completed",
44 "spent",
45 "received",
46 "fees",
47 "created_at",
48 ]
49 read_only_fields = fields
51 def get_spent(self, instance):
52 """Return spend informations."""
53 exit_amount = instance.exit_amount_quote if instance.side == SIDES.BUY else instance.exit_amount_base
54 amount = instance.debited_amount - exit_amount
55 ticker = instance.tickers_info().get("spent_ticker")
56 return {
57 "ticker": ticker,
58 "amount": amount,
59 "price": 1,
60 "value": amount,
61 }
63 def get_received(self, instance):
64 """Rerturn receive informations."""
65 amount = instance.exit_amount_base if instance.side == SIDES.BUY else instance.exit_amount_quote
66 ticker = instance.tickers_info().get("received_ticker")
67 price = instance.price
68 return {
69 "ticker": ticker,
70 "amount": amount,
71 "price": price,
72 "value": amount * price,
73 }
75 def get_fees(self, instance):
76 return {
77 "ticker": instance.fee_ticker,
78 "amount": instance.fees,
79 "value": instance.fees * instance.price,
80 }
82 def save(self, **kwargs):
83 error_msg: str = "It's impossible to create ormodify an order."
84 raise serializers.ValidationError(error_msg)