Ejemplo n.º 1
0
    def get_orderbook(self, currency: OkcoinCurrency):
        res = self._session.get(self.BASE_URL +
                                "/depth.do?symbol=%s" % currency.value)
        res_json = self.filter_successful_response(res)

        # normalize asks
        _asks = res_json["asks"]
        asks = list()

        # min ask positioned at the last... exceptional case only for Okcoin
        reversed_asks = list(reversed(_asks))
        for _ask in reversed_asks[:30]:
            ask = {
                "price": Decimal128(str(_ask[0])),
                "amount": Decimal128(str(_ask[1]))
            }
            asks.append(ask)

        # normalize bids
        _bids = res_json["bids"]
        bids = list()
        for _bid in _bids[:30]:
            bid = {
                "price": Decimal128(str(_bid[0])),
                "amount": Decimal128(str(_bid[1]))
            }
            bids.append(bid)

        # reformat result
        result = {"asks": asks, "bids": bids}

        return result
Ejemplo n.º 2
0
    def get_orderbook(self, currency: BithumbCurrency):
        res = self._session.get(self.BASE_URL +
                                "/public/orderbook/%s" % currency.value)
        res_json = self.filter_successful_response(res)

        # normalize asks
        _asks = res_json["data"]["asks"]
        asks = list()
        for _ask in _asks[:30]:
            ask = {
                "price": Decimal128(str(_ask["price"])),
                "amount": Decimal128(str(_ask["quantity"]))
            }
            asks.append(ask)

        # normalize bids
        _bids = res_json["data"]["bids"]
        bids = list()
        for _bid in _bids[:30]:
            bid = {
                "price": Decimal128(str(_bid["price"])),
                "amount": Decimal128(str(_bid["quantity"]))
            }
            bids.append(bid)

        # reformat result
        result = {"asks": asks, "bids": bids}

        return result
Ejemplo n.º 3
0
def test_can_get_bet(mongodb: Database) -> None:
    # given
    repo = MongoDBBetRepository()  # type: ignore

    # when
    bet_id = ObjectId()
    mongodb["bet"].insert_one({
        "_id": bet_id,
        "opponent_1": "test 1",
        "opponent_2": "test 2",
        "odds_1": Decimal128("4.12"),
        "odds_2": Decimal128("3.56"),
        "category": Category.ESPORT.value,
        "provider": Provider.EFORTUNA.value,
        "date": datetime.utcnow(),
        "url": "/test/bet/url",
        "updated_at": datetime.utcnow(),
        "created_at": datetime.utcnow(),
    })

    # and
    bet = repo.get(bet_id)

    # then
    assert isinstance(bet, Bet)
    assert bet.id == bet_id
    assert bet.opponent_1 == "test 1"
    assert bet.opponent_2 == "test 2"
    assert bet.odds_1.compare(Decimal(4.12))
    assert bet.odds_2.compare(Decimal(3.56))
    assert bet.url == "/test/bet/url"
Ejemplo n.º 4
0
    def test_bson_classes(self):
        _id = '5a918f9fa08bff9c7688d3e1'

        for a, b in [
            (Binary(b'foo'), Binary(b'foo')),
            (Code('foo'), Code('foo')),
            (Code('foo', {'x': 1}), Code('foo', {'x': 1})),
            (DBRef('coll', 1), DBRef('coll', 1)),
            (DBRef('coll', 1, 'db'), DBRef('coll', 1, 'db')),
            (Decimal128('1'), Decimal128('1')),
            (MaxKey(), MaxKey()),
            (MinKey(), MinKey()),
            (ObjectId(_id), ObjectId(_id)),
            (Regex('foo', 'i'), Regex('foo', 'i')),
            (Timestamp(1, 2), Timestamp(1, 2)),
        ]:
            # Basic case.
            self.assertTrue(
                Matcher(Command(y=b)).matches(Command(y=b)),
                "MockupDB %r doesn't equal itself" % (b, ))

            # First Command argument is special, try comparing the second also.
            self.assertTrue(
                Matcher(Command('x', y=b)).matches(Command('x', y=b)),
                "MockupDB %r doesn't equal itself" % (b, ))

            # In practice, users pass PyMongo classes in message specs.
            self.assertTrue(
                Matcher(Command(y=b)).matches(Command(y=a)),
                "PyMongo %r != MockupDB %r" % (a, b))

            self.assertTrue(
                Matcher(Command('x', y=b)).matches(Command('x', y=a)),
                "PyMongo %r != MockupDB %r" % (a, b))
Ejemplo n.º 5
0
    def get_orderbook(self, currency: CoinnestCurrency):
        res = self._session.get(self.BASE_URL +
                                "/api/pub/depth?coin=%s" % currency.value)
        res_json = self.filter_successful_response(res)

        # normalize asks
        _asks = res_json["asks"]
        asks = list()
        for _ask in _asks[:30]:
            ask = {
                "price": Decimal128(str(_ask[0])),
                "amount": Decimal128(str(_ask[1]))
            }
            asks.append(ask)

        # normalize bids
        _bids = res_json["bids"]
        bids = list()
        for _bid in _bids[:30]:
            bid = {
                "price": Decimal128(str(_bid[0])),
                "amount": Decimal128(str(_bid[1]))
            }
            bids.append(bid)

        # reformat result
        result = {"asks": asks, "bids": bids}

        return result
Ejemplo n.º 6
0
    def get_orderbook(self, currency: CoinoneCurrency):
        res = self._session.get(self.BASE_URL + "/orderbook",
                                params={"currency": currency.value})
        res_json = self.filter_successful_response(res)

        # normalize asks
        _asks = res_json["ask"]
        asks = list()
        for _ask in _asks[:orderbook_item_limit]:
            ask = {
                "price": Decimal128(_ask["price"]),
                "amount": Decimal128(_ask["qty"])
            }
            asks.append(ask)

        # normalize bids
        _bids = res_json["bid"]
        bids = list()
        for _bid in _bids[:orderbook_item_limit]:
            bid = {
                "price": Decimal128(_bid["price"]),
                "amount": Decimal128(_bid["qty"])
            }
            bids.append(bid)

        # reformat result
        result = {
            "timestamp": int(res_json["timestamp"]),
            "asks": asks,
            "bids": bids,
        }

        return result
Ejemplo n.º 7
0
def addsign():
    if not current_user.is_authenticated:
        flash(f"Please login to upload a sign", "danger")
        return redirect(url_for('home'))
    form = FileUploadForm()
    if form.validate_on_submit():
        f = form.photo.data
        filename = secure_filename(f.filename)
        ext = filename.split('.')[1]
        newfilename = uuid.uuid4().hex + '.' + ext
        filepath = os.path.join(app.instance_path, 'media/img', newfilename)
        #f.save(filepath)
        resize_picture((260, 180), form.photo.data, filepath)
        user_dict = db.users.find_one({"_id": ObjectId(current_user.get_id())})
        del user_dict["password"]
        sign_dict = {
            "title": form.title.data,
            "wherefound": form.wherefound.data,
            "file": newfilename,
            "creator": user_dict,
            "created": datetime.datetime.now(),
            "location": {
                "type":
                "Point",
                "coordinates":
                [Decimal128(form.long.data),
                 Decimal128(form.lat.data)]
            }
        }
        sign_id = db.signs.insert_one(sign_dict)
        return redirect(url_for('latest'))
    return render_template('addsign.html', form=form)
Ejemplo n.º 8
0
    def get_orderbook(self, currency: GopaxCurrency):
        res = self._session.get(self.BASE_URL + "/trading-pairs/%s/book" % currency.value)
        res_json = self.filter_successful_response(res)

        # normalize asks
        _asks = res_json["ask"]
        asks = list()
        for _ask in _asks[:30]:
            ask = {
                "price": Decimal128(str(_ask[1])),
                "amount": Decimal128(str(_ask[2]))
            }
            asks.append(ask)

        # normalize bids
        _bids = res_json["bid"]
        bids = list()
        for _bid in _bids[:30]:
            bid = {
                "price": Decimal128(str(_bid[1])),
                "amount": Decimal128(str(_bid[2]))
            }
            bids.append(bid)

        # reformat result
        result = {
            "asks": asks,
            "bids": bids
        }

        return result
Ejemplo n.º 9
0
    def get_orderbook(self, currency: KorbitCurrency):
        res = self._session.get(self.BASE_URL + "/v1/orderbook", params={
            "currency_pair": currency.value
        })
        res_json = self.filter_successful_response(res)

        # normalize asks
        _asks = res_json["asks"]
        asks = list()
        for _ask in _asks:
            ask = {
                "price": Decimal128(_ask[0]),
                "amount": Decimal128(_ask[1])
            }
            asks.append(ask)

        # normalize bids
        _bids = res_json["bids"]
        bids = list()
        for _bid in _bids:
            bid = {
                "price": Decimal128(_bid[0]),
                "amount": Decimal128(_bid[1])
            }
            bids.append(bid)

        # reformat result
        result = {
            "timestamp": res_json["timestamp"],
            "asks": asks,
            "bids": bids,
        }

        return result
Ejemplo n.º 10
0
def test_d128_set():
    doc = Doc()

    doc.dec128 = Decimal128('3.14')
    assert doc.dec128 == Decimal128('3.14')

    doc.dec128 = '13'
    assert doc.dec128 == Decimal128('13')
    def test_simple(self):
        codecopts = self._get_codec_options(lambda x: Decimal128(x))
        document = {'average': Decimal('56.47')}
        bsonbytes = encode(document, codec_options=codecopts)

        exp_document = {'average': Decimal128('56.47')}
        exp_bsonbytes = encode(exp_document)
        self.assertEqual(bsonbytes, exp_bsonbytes)
Ejemplo n.º 12
0
def tx_to_dict(tx):
    result = {}
    for key, val in tx.items():
        if isinstance(val, HexBytes):
            result[key] = val.hex()
        else:
            result[key] = val

    if 'value' in result: result['value'] = Decimal128(str(result['value']))
    if 'gasPrice' in result: result['gasPrice'] = Decimal128(str(result['gasPrice']))

    return result
Ejemplo n.º 13
0
def block_to_dict(tx):
    result = {}
    for key, val in tx.items():
        if isinstance(val, HexBytes):
            result[key] = val.hex()
        else:
            result[key] = val

    if 'difficulty' in result: result['difficulty'] = Decimal128(str(result['difficulty']))
    if 'totalDifficulty' in result: result['totalDifficulty'] = Decimal128(str(result['totalDifficulty']))

    return result
Ejemplo n.º 14
0
 def get_ofertas_por_faixa_de_preco(self, pmin, pmax, limite: int, offset: int):
     """
     Retorna todas as ofertas que correspondam à faixa de preço passada [pmin, pmax]
     """
     ofertas = self.items.find({'preco': {'$gte': Decimal128(pmin), '$lte': Decimal128(pmax)}},
                               projection={'titulo': True,
                                           'moeda': True,
                                           'preco': True,
                                           'disponivel': True}, skip=offset, limit=limite)
     resultado = []
     for oferta in ofertas:
         resultado.append(oferta)
     return resultado
Ejemplo n.º 15
0
    def get_ticker(self, currency: KorbitCurrency):
        res = self._session.get(self.BASE_URL + "/v1/ticker/detailed", params={
            "currency_pair": currency.value
        })
        res_json = self.filter_successful_response(res)

        # reformat result
        result = {
            "timestamp": res_json["timestamp"],
            "high": Decimal128(res_json["high"]),
            "low": Decimal128(res_json["low"]),
            "last": Decimal128(res_json["last"]),
            "minAsk": Decimal128(res_json["ask"]),
            "maxBid": Decimal128(res_json["bid"]),
            "volume": Decimal128(res_json["volume"])
        }

        # change & changePercent are not specified in official API
        # just to make sure in order to avoid KeyError
        change = res_json.get("change")
        change_percent = res_json.get("changePercent")

        if change is not None:
            result["change"] = Decimal128(change)

        if change_percent is not None:
            result["changePercent"] = Decimal128(change_percent)

        return result
Ejemplo n.º 16
0
    def get_ticker(self, currency: GopaxCurrency):
        res = self._session.get(self.BASE_URL + "/trading-pairs/%s/stats" % currency.value)
        res_json = self.filter_successful_response(res)

        # reformat result
        result = {
            "timestamp": Global.iso8601_to_unix(res_json["time"]),
            "open": Decimal128(str(res_json["open"])),
            "close": Decimal128(str(res_json["close"])),
            "high": Decimal128(str(res_json["high"])),
            "low": Decimal128(str(res_json["low"])),
            "volume": Decimal128(str(res_json["volume"]))
        }

        return result
Ejemplo n.º 17
0
def add_diner():
    diner_coll = mongo.db.DinerLocation
    worker_coll = mongo.db.Workers
    balance_coll = mongo.db.Balance
    result = []
    workers = []
    operation = request.get_json()
    time_details = operation['details']
    count = len(time_details)
    current_balance = Decimal128('0')
    for field in worker_coll.find():
        for i in range(count):
            if field['name'] == time_details[i]['worker']['name']:
                new_balance = Decimal128(
                    Decimal(time_details[i]['given']) +
                    Decimal(time_details[i]['get']))
                current_balance = Decimal128(current_balance.to_decimal() +
                                             new_balance.to_decimal())
    if current_balance != Decimal128('0'):
        if current_balance != Decimal128('0.0'):
            return 'Check amount is not 0'
    for field in worker_coll.find():
        for i in range(count):
            if field['name'] == time_details[i]['worker']['name']:
                workers.append({
                    'worker': {
                        'idWorker': field['_id']
                    },
                    'given': time_details[i]['given'],
                    'get': time_details[i]['get']
                })
                new_balance = Decimal128(
                    Decimal(time_details[i]['given']) +
                    Decimal(time_details[i]['get']))
                if new_balance != Decimal128('0.0'):
                    balance_now = balance_coll.find_one(
                        {'workerId': field['_id']})
                    time_balance = Decimal128(
                        balance_now['balance'].to_decimal() +
                        new_balance.to_decimal())
                    balance_coll.update_one(
                        {'_id': balance_now['_id']},
                        {'$set': {
                            'balance': time_balance
                        }})
    time_diner = diner.Diner.make_diner({
        'title': operation['title'],
        'date': operation['date'],
        'details': workers
    })
    data = {
        'title': time_diner.title,
        'date': time_diner.date,
        'details': time_diner.details
    }
    diner_coll.insert(data)
    result.append(data)
    return json.dumps(result, ensure_ascii=False, default=str)
Ejemplo n.º 18
0
    def create_shot(self, event):
        ts = event["ts"]
        channel = event["channel"]
        user = event["user"]
        lst = list_users(event)
        week = get_week(self.season)

        if self.season:
            season = self.season["name"]
        else:
            season = "none"

        if len(lst) > 0:
            db[self.team_id + 'shots'].insert_one({
                "ts": Decimal128(ts),
                "channel": channel,
                "user": user,
                "targets": lst,
                "week": week,
                "season": season,
                "plus": -1,
                "trash": -1
            })

            token = self.get_oauth()
            react(channel, ts, token, environ["PLUS_REACTION"])
            react(channel, ts, token, environ["TRASH_REACTION"])
            print(f"Shot {ts} created.")
        else:
            pass
Ejemplo n.º 19
0
def addExpenses():
    # INCLUDE THE FORM
    expensesForm = Expenses()
    if request.method == "POST":
        # INSERT ONE DOCUMENT TO THE DATABASE
        # CONTAINING THE DATA LOGGED BY THE USER
        # REMEMBER THAT IT SHOULD BE A PYTHON DICTIONARY
        input_description = expensesForm.description.data
        input_category = expensesForm.category.data
        input_cost = expensesForm.cost.data
        input_date = expensesForm.date.data
        input_currency = expensesForm.currency.data

        final_cost = currency_converter(input_cost, input_currency)

        if input_cost:
            expense = {
                'description': input_description,
                'category': input_category,
                'cost': Decimal128(Decimal(str(final_cost))),
                'date': str(input_date)
            }

            mongo.db.expenses.insert_one(expense)

            return render_template("expenseAdded.html")
    return render_template("addExpenses.html", form=expensesForm)
Ejemplo n.º 20
0
 def deposite(self, args):
     self.logger.debug("Entering desposite")
     ##if the number is negative or not in decimal format then give error and prompt again.
     if len(args) > 1 and args[1].replace('.', '', 1).isdigit():
         deposite_dec = Decimal(args[1])
         account = self.authorization_svc.get_active_account()
         acct_bal = Decimal(str(account.get("balance")))
         final_balance_dec = acct_bal + deposite_dec
         final_balance_pretty = self.pretty_money(final_balance_dec)
         final_balance_dec128 = Decimal128(str(final_balance_dec))
         aid = account.get("account_id")
         #if user save is succesful we save the user's history and refresh the active account
         if self.account_data_svc.save_transaction(aid,
                                                   final_balance_dec128):
             self.logger.info("Deposite succesful for account: " + str(aid))
             self.authorization_svc.refresh(aid)
             self.balance()
             deposite_pretty = self.pretty_money(deposite_dec)
             self.account_data_svc.update_history(aid, deposite_pretty,
                                                  final_balance_pretty)
     else:
         print(
             "Expected a non negative decimal value in non-scientific format"
         )
     self.logger.debug("Exiting desposite")
Ejemplo n.º 21
0
def post_book():
    """Post book data from users input.

    This is used as the acton attribute on the add book form,
    then uses that new book to pass the ObjectId as a variable.

    Returns:
        the user is redirected to the new book they have input.
        along with the book_id variable.

    """
    now = datetime.now().timestamp()
    mongo.db.books.insert_one({
        "user_rating_average":
        None,
        "title":
        request.form.get("title"),
        "authors":
        request.form.get("authors"),
        "original_publication_year":
        request.form.get("year"),
        "description":
        request.form.get("description"),
        "image_url":
        request.form.get("image"),
        "posted_by":
        session["user"],
        "time_added":
        now,
        "average_rating":
        Decimal128("0")
    })
    book_id = mongo.db.books.find_one({"title": request.form.get("title")})

    return redirect(url_for("get_one_book", book_id=book_id["_id"]))
Ejemplo n.º 22
0
class Details:
    worker = []
    given = Decimal128("0.0")
    get = Decimal128("0.0")

    def __init__(self, detail):
        self.worker = detail['worker']
        self.given = detail['given']
        self.get = detail['get']

    @staticmethod
    def make_details(detail):
        time_detail = []
        count = len(detail)
        for i in range(count):
            time_detail.append(Details(detail[i]))
        return time_detail
Ejemplo n.º 23
0
 def _validate(self, value, **kw):
     value = super(NumberDecimal, self)._validate(value, **kw)
     if isinstance(value, Decimal128):
         value = value.to_decimal()
     value = self._context.create_decimal(value)
     if self.precision:
         value = value.quantize(self._quantizing, rounding=self.rounding)
     return Decimal128(value)
Ejemplo n.º 24
0
 def prepare_value(self, document: BaseDocument,
                   value: TDecimal128able) -> Decimal:
     if isinstance(value, Decimal128):
         return value
     elif isinstance(value, (str, Decimal)):
         return Decimal128(value)
     else:  # pragma: no cover
         raise TypeError(value)
 def apply_history_to_orderbook(self, orderbook: dict):
     history_keys = self.history.keys()
     for order in orderbook["asks"]:
         price = int(order["price"].to_decimal())
         if price in history_keys:
             order["amount"] = Decimal128(order["amount"].to_decimal() +
                                          Decimal(self.history[price]))
             if order["amount"].to_decimal() < 0:
                 order["amount"] = Decimal128("0")
     for order in orderbook["bids"]:
         price = int(order["price"].to_decimal())
         if price in history_keys:
             order["amount"] = Decimal128(order["amount"].to_decimal() -
                                          Decimal(self.history[price]))
             if order["amount"].to_decimal() < 0:
                 order["amount"] = Decimal128("0")
     return orderbook
 def _generate_multidocument_bson_stream(self):
     inp_num = [str(random() * 100)[:4] for _ in range(10)]
     docs = [{'n': Decimal128(dec)} for dec in inp_num]
     edocs = [{'n': Decimal(dec)} for dec in inp_num]
     bsonstream = b""
     for doc in docs:
         bsonstream += encode(doc)
     return edocs, bsonstream
Ejemplo n.º 27
0
    def from_mongo(self, value):
        if value is None:
            return None

        if not isinstance(value, Decimal128):
            value = Decimal128(str(value))

        return value.to_decimal()
Ejemplo n.º 28
0
    def get_filled_orders(self, currency: KorbitCurrency, time_range: str = "hour"):
        res = self._session.get(self.BASE_URL + "/v1/transactions", params={
            "currency_pair": currency.value,
            "time": time_range
        })
        res_json = self.filter_successful_response(res)

        result = list()
        for _item in res_json:
            item = {
                "timestamp": _item["timestamp"],
                "price": Decimal128(_item["price"]),
                "amount": Decimal128(_item["amount"])
            }
            result.append(item)

        return result
Ejemplo n.º 29
0
async def increase_days(
        users: AsyncIOMotorCollection,
        leave_type: str,
        days: Decimal,
) -> None:
    await users.update_many(
        {},
        {'$inc': {f'days.{leave_type}': Decimal128(days)}}
    )
Ejemplo n.º 30
0
class Balance:
    workerId = ""
    balance = Decimal128("0.0")

    def __init__(self, balance):
        self.workerId = balance['workerId']

    @staticmethod
    def make_balance(balance):
        return Balance(balance)