Exemplo n.º 1
0
def balance_accounts(order, candidate, initial_order_amount_completed,
                     initial_candidate_amount_completed):
    account_order = Account.objects.get(user=order.user)
    account_candidate = Account.objects.get(user=candidate.user)

    order_amount_completed = order.amount_completed - initial_order_amount_completed
    candidate_amount_completed = candidate.amount_completed - initial_candidate_amount_completed

    if order_amount_completed != candidate_amount_completed:
        raise RuntimeError('Amounts should be the same!')

    # todo: check again for prices
    if order.what == BTC and order.order_type == BUY:
        account_order.btc = account_order.btc + order_amount_completed
        account_candidate.btc = account_candidate.btc - candidate_amount_completed
    elif order.what == LTC and order.order_type == BUY:
        account_order.ltc = account_order.ltc + order_amount_completed
        account_candidate.ltc = account_candidate.ltc - candidate_amount_completed
    elif order.what == BTC and order.order_type == SELL:
        account_order.btc = account_order.btc - order_amount_completed
        account_candidate.btc = account_candidate.btc + candidate_amount_completed
    elif order.what == LTC and order.order_type == SELL:
        account_order.ltc = account_order.ltc - order_amount_completed
        account_candidate.ltc = account_candidate.ltc + candidate_amount_completed

    for_how_much = None
    price = None

    if order.order_type == BUY:
        # important that we use candidates price
        for_how_much = order_amount_completed * candidate.price
        price = candidate.price

        if order.trade_currency == EUR:
            account_order.eur = account_order.eur - for_how_much
            account_candidate.eur = account_candidate.eur + for_how_much
        elif order.trade_currency == USD:
            account_order.usd = account_order.usd - for_how_much
            account_candidate.usd = account_candidate.usd + for_how_much
    elif order.order_type == SELL:
        # important that we use order price
        for_how_much = order_amount_completed * order.price
        price = order.price

        if order.trade_currency == EUR:
            account_order.eur = account_order.eur + for_how_much
            account_candidate.eur = account_candidate.eur - for_how_much
        elif order.trade_currency == USD:
            account_order.usd = account_order.usd + for_how_much
            account_candidate.usd = account_candidate.usd - for_how_much

    account_order.save()
    account_candidate.save()

    trade = Trade(order=order,
                  candidate=candidate,
                  amount=order_amount_completed,
                  price=price,
                  total=for_how_much)
    trade.save()
Exemplo n.º 2
0
    def test_is_fair_only_experience(self):
        self.assertTrue(fairness.is_fair(trade))
        pokemon1 = {'name': 'pikachu', 'base_experience': 112, 'image': 'url'}
        pokemon2 = {
            'name': 'charmander',
            'base_experience': 62,
            'image': 'url'
        }
        trade2 = Trade()
        trade2.left_side = [pokemon1]
        trade2.right_side = [pokemon2]

        self.assertFalse(fairness.is_fair(trade2))
Exemplo n.º 3
0
    def verify(self, request):
        """
        Verify if a specific Trade is fair or not.
        It receive a POST request containing a Trade data in JSON format
        and return the same Trade with the result (is fair or not).
        """
        trade_serializer = TradeSerializer(data=request.data)
        if trade_serializer.is_valid():
            trade = Trade(right_side=trade_serializer.validated_data['right_side'],
                          left_side=trade_serializer.validated_data['left_side'])

            trade_serializer.validated_data['result'] = trade.is_fair()

            return Response(trade_serializer.validated_data, status=status.HTTP_200_OK)
        return Response(trade_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 4
0
def profile(request, username):
    if username == request.user.username:
        return render(request, "accounts/my_profile.html", dict(
            non_returned_equipment_ownerships=request.user.equipments.all(),
            day_grouped=Job.group_by_date(request.user.jobs.all()),
        ))

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise Http404("Kunde inte hitta användaren '%s'" % username)

    jobs = misc_utils.filter_jobs_for_user(request.user, user.jobs)

    day_grouped = Job.group_by_date(jobs)

    if request.user.is_anonymous:
        trade = None
    else:
        try:
            trade = Trade.get_trade(request.user, user)
        except Trade.DoesNotExist:
            trade = None

    return render(request, "accounts/profile.html", dict(
        user=user,
        day_grouped=day_grouped,
        trade=trade,
    ))
Exemplo n.º 5
0
    def create(self, validated_data):
        trade = Trade(**validated_data)
        next_pk = get_next_pk()
        if next_pk > UID_MAX_REPR_VALUE:
            raise ValidationError("Can't create more trades")

        trade.id = pk_to_id(next_pk)
        rate = get_rate(trade.sell_currency, trade.buy_currency)
        trade.sell_amount = trade.sell_amount
        trade.buy_amount = round_decimal(trade.sell_amount * rate,
                                         DECIMAL_PLACES)
        trade.rate = round_decimal(rate, DECIMAL_PLACES)
        trade.save()
        return trade
def create_default_trade():
    pokemon1 = {'name': 'pikachu', 'base_experience': 112, 'image': 'url'}
    pokemon2 = {'name': 'charmander', 'base_experience': 62, 'image': 'url'}
    trade = Trade()
    trade.right_side = [pokemon1, pokemon2]
    trade.left_side = [pokemon1, pokemon2]
    trade.result = trade.is_fair()

    return trade
Exemplo n.º 7
0
    def save(self, request):
        """
        Save a specific trade in database. It is done if the user accept the trade.
        It is used to populate the database with all trades that was made with PokeTrader.
        """
        trade_serializer = TradeSerializer(data=request.data)
        if trade_serializer.is_valid():
            trade = Trade(right_side=trade_serializer.validated_data['right_side'],
                          left_side=trade_serializer.validated_data['left_side'])
            trade.result = trade.is_fair()

            trade.save()
            return Response(trade_serializer.validated_data, status=status.HTTP_200_OK)
        return Response(None, status=status.HTTP_400_BAD_REQUEST)
async def main(client, symbol, exchange):

    count_before_fetch = Trade.objects.filter(exchange=exchange,
                                              symbol=symbol).count()

    ticks = await client.ticks(symbol)
    _data = []
    for d in ticks["data"]:
        _data.extend(d["data"])

    logger.info(f"client returned {len(_data)} records")

    _trade_objs = []

    for trade in _data:
        _price = Decimal(trade["price"])
        _amount = Decimal(trade["amount"])

        _trade_objs.append(
            Trade(
                exchange=exchange,
                symbol=symbol,
                trade_time=ts_to_dt(trade["ts"] / 1000),
                price=_price,
                amount=_amount,
                value=_price * _amount,
            ))

    Trade.objects.bulk_create(_trade_objs, ignore_conflicts=True)

    count_after_fetch = Trade.objects.filter(exchange=exchange,
                                             symbol=symbol).count()

    logger.info(
        f"after fetch, the number of trade ({symbol} @ {exchange}): {count_before_fetch} ==> {count_after_fetch}"
    )