class CurrencyTests(TestCase):

    dollar = Currency(
        symbol='$', code='USD', name='US Dollar',
        name_plural='US dollars', decimal_digits=2,
        is_master=True, active=True, exchange_rate=1
    )
    argentine_peso = Currency(
        symbol='AR$', code='ARS', name='Argentine Peso',
        name_plural='Argentine Pesos', decimal_digits=2,
        is_master=False, active=True, exchange_rate=0.023
    )
    japanese_yen = Currency(
        symbol='¥', code='JPY', name='Japanese Yen',
        name_plural='Japanese Yen', decimal_digits=0,
        is_master=False, active=True, exchange_rate=0.0093
    )

    def test_to_string(self):
        self.assertEquals(str(self.dollar), 'USD - US Dollar')
        self.assertNotEqual(str(self.japanese_yen), '¥ - Japanese Yen')
        logger.info('Logging Info Example with name of the module')

    def test_value_equivalence_to_other_currency(self):
        to_round = self.japanese_yen.value_equivalence_to_other_currency(1, self.argentine_peso.exchange_rate)
        self.assertEquals(round(to_round, 1), 2.5)

        value_to_check = self.dollar.value_equivalence_to_other_currency(100, self.dollar.exchange_rate)
        self.assertEquals(value_to_check, 100.0)
예제 #2
0
 def handle(self, *args, **kwargs):
     url = base_url + urllib.parse.urlencode(url_parameters)
     self.stdout.write("Fetching from:\n" + url)
     fetched_data = requests.get(url).json()
     price_timestamp = {}
     for row in fetched_data:
         curr = None
         if Currency.objects.filter(name=row['id']).exists():
             curr = Currency.objects.get(name=row['id'])
             curr.symbol = row['symbol']
             curr.current_price = row['current_price']
             curr.market_cap = row['market_cap']
             curr.total_volume = row['total_volume']
             curr.high_24h = row['high_24h']
             curr.low_24h = row['low_24h']
             curr.price_change_24h = row['price_change_24h']
             curr.price_change_percentage_24h = row[
                 'price_change_percentage_24h']
         else:  # creates new record
             curr = Currency(name=row['id'],
                             symbol=row['symbol'],
                             current_price=row['current_price'],
                             market_cap=row['market_cap'],
                             total_volume=row['total_volume'],
                             high_24h=row['high_24h'],
                             low_24h=row['low_24h'],
                             price_change_24h=row['price_change_24h'],
                             price_change_percentage_24h=row[
                                 'price_change_percentage_24h'])
         curr.save()
         price_timestamp[curr.name] = curr.current_price
     prices = json.dumps(price_timestamp)
     self.stdout.write(prices)
예제 #3
0
def set_default_currency():
    try:
        currency = Currency(code='USD', name='US Dollar', symbol='$')
    except Exception as e:
        logging.debug('Exception occured in creating default currency', str(e))
    else:
        currency.save()
예제 #4
0
 def handle(self, *args, **options):
     try:
         Currency.cbr_load()
     except Currency.CbrLoadException as e:
         raise CommandError(f'Error while loading currencies: {e}')
     except Exception as e:
         raise CommandError(
             f'Unhandled error while loading currencies: {e}')
     else:
         self.stdout.write(
             self.style.SUCCESS("Currencies loaded successfully"))
         for c in Currency.objects.all():
             self.stdout.write(f"{c}\n")
예제 #5
0
 def get_available_products(user):
     qs = Product.objects.filter(is_deleted=False)
     user_currency = user.currency
     print(user_currency)
     if user_currency:
         Currency.updating_latest_values()
         user_currency_current_value = Currency.objects.get(
             id=user_currency.id).value
         print(user_currency_current_value)
         qs = qs.annotate(
             user_currency_price=(models.F('price') /
                                  models.F('currency__value')) *
             user_currency_current_value)
     return qs
예제 #6
0
    def handle(self, *args, **options):
        print("Querying database at %s" % (CURRENCY_API_URL))

        currencies = []
        if len(args):
            currencies = list(args)

        api = urlopen(CURRENCY_API_URL)
        d = json.loads(api.read())
        i = 0

        for currency in sorted(d.keys()):
            if (not currencies) or currency in currencies:
                if not Currency.objects.filter(code=currency):
                    print("Creating %r (%s)" % (d[currency], currency))
                    Currency(code=currency,
                             name=d[currency],
                             factor=1.0,
                             is_active=False).save()
                    i += 1

        if i == 1:
            print("%i new currency" % (i))
        else:
            print("%i new currencies" % (i))
class AccountAndAccountLogBaseTestCase(APITestCase):

    argentine_peso = Currency(symbol='AR$',
                              code='ARS',
                              name='Argentine Peso',
                              name_plural='Argentine Pesos',
                              decimal_digits=2,
                              is_master=False,
                              active=True,
                              exchange_rate=0.023)
    dollar = Currency(symbol='$',
                      code='USD',
                      name='US Dollar',
                      name_plural='US dollars',
                      decimal_digits=2,
                      is_master=True,
                      active=True,
                      exchange_rate=1)
    pesos_test_account = None
    dollars_test_account = None

    def get_token(self):
        url = reverse('token_obtain_pair')
        return self.client.post(url, {
            'username': '******',
            'password': '******'
        },
                                format='json').data['access']

    def setUp(self):
        User.objects.create_user('test111', '*****@*****.**',
                                 'testtttt1232').save()
        User.objects.create_user('test222', '*****@*****.**',
                                 'testtttt1232').save()
        self.argentine_peso.save()
        self.dollar.save()
        self.pesos_test_account = Account.objects.create(
            balance=100.0,
            owner=User.objects.get(username='******'),
            currency=self.argentine_peso)
        self.dollars_test_account = Account.objects.create(
            balance=100.0,
            owner=User.objects.get(username='******'),
            currency=self.dollar)
        self.pesos_test_account.save()
        self.dollars_test_account.save()
예제 #8
0
def import_currencies():
    currencies = get_currencies_from_xml()
    db_currencies = Currency.objects.all()

    for db_currency in db_currencies:
        if db_currency.name not in currencies:
            db_currency.delete()

    for name, rate in currencies.items():
        try:
            db_currency = Currency.objects.get(name=name)
            db_currency.name = name
            db_currency.rate = rate
        except Currency.DoesNotExist:
            db_currency = Currency(name=name, rate=rate)

        db_currency.save()
예제 #9
0
    def get(self, request):
        #TODO: remove hardcoding
        data = urllib.request.urlopen("url...").read()
        data = json.loads(data)

        for currency in data:
            try:
                cur = Currency.objects.get(currency_id=currency['id'])
            except Currency.DoesNotExist:
                cur = Currency()
                cur.populate_from_dict(currency)
                cur.save()

            history = CurrencyHistory()
            history.populate_from_dict(currency)
            history.currency = cur
            history.save()

        return HttpResponse(data, content_type="application/json")
예제 #10
0
from exchanges.models import Exchange
from currencies.models import Currency, CurrencyPair
from exchanges.apis.manager import ClientManager
""" This script pulls individial cryptocurrencies and currency currency pairs from
    all exchanges and saves them to DB"""

client = ClientManager(**keys)
for exchange in exchanges:
    print(exchange)
    exchange = Exchange.objects.get(name=exchange)
    currencies = client.get_currencies(exchange.name.lower())
    for currency in currencies:
        if not Currency.objects.filter(symbol=currency,
                                       exchange=exchange).exists():
            new_currency = Currency()
            new_currency.exchange = exchange
            new_currency.symbol = currency
            if currency == "USDT" or currency == "USDC":
                new_currency.name = "USD"
            else:
                new_currency.name = currency
            new_currency.save()

for exchange in exchanges:
    exchange = Exchange.objects.get(name=exchange)
    currency_pairs = client.get_currency_pairs(exchange.name.lower())
    for currency_pair in currency_pairs:
        base = Currency.objects.get(symbol=currency_pair['base'],
                                    exchange=exchange)
        quote = Currency.objects.get(symbol=currency_pair['quote'],