Пример #1
0
def drange3(start, end, stepsize, toInt=False):
    """
    momentum increment from start to end by stepsize
    e.g. drange3(0, 1, 0.1)
        [0.0, 0.1, 0.22, 0.413907, 0.842504]
    """
    assert stepsize < (abs(start - end))

    from decimal import Decimal, getcontext

    getcontext().prec = 6

    momentum = Decimal(2)
    increment = Decimal(start)
    stepsize = Decimal(stepsize)
    res = list()
    while increment <= end:
        if toInt:
            res.append(int(increment.__float__()))
        else:
            res.append(increment.__float__())

        increment += stepsize
        stepsize *= (Decimal(0.6) * momentum)
        momentum = Decimal(momentum + momentum.ln())

    return res
Пример #2
0
def sphere_of_influence(planet):
	''' This function calculates the effective sphere of influence of a planet'''
	massPlanet = Decimal(planets[planet.capitalize()]['mu']) / Decimal(6.67384*pow(10,-11))
	massSun = Decimal(planets[planets[planet]['Parent']]['mu']) / Decimal(6.67384*pow(10,-11))
	average = Decimal(planets[planet.capitalize()]['Ap'] + planets[planet.capitalize()]['Po']) / Decimal(2)
	exponent = Decimal(2)/Decimal(5)
	soi = Decimal(average)*(Decimal(massPlanet)/Decimal(massSun))**exponent
	return soi.__float__()
Пример #3
0
 def product_tax_calculator(self, tax_rate):
     """ Return product final price based on the provided `tax_rate`
     Decimal module used for precision and rounding purposes
     """
     #setup decimal context
     getcontext().prec = 4
     getcontext().round = ROUND_HALF_EVEN
     total = Decimal(self.price) * Decimal(tax_rate)
     self.product_tax = round_nearest(total.__float__())
     return round(float(self.price) + self.product_tax, 2)
Пример #4
0
def drange2(start, end, stepsize, toInt=False):
    """
    increment from start to end by stepsize
    """
    assert stepsize < (abs(start - end))

    from decimal import Decimal, getcontext

    getcontext().prec = 6

    increment = Decimal(start)
    stepsize = Decimal(stepsize)
    res = list()
    while increment <= end:
        if toInt:
            res.append(int(increment.__float__()))
        else:
            res.append(increment.__float__())
        increment += stepsize

    return res
Пример #5
0
class FixedExpense:
    name: str
    split: bool
    amount: Decimal

    def __init__(self, name: str, info: dict):
        self.name = name
        self.split = info.get('split') or False
        self.amount = Decimal(info['amount'])

    def __str__(self):
        return '%s: $%.02f' % (self.name, self.amount.__float__())

    __repr__ = __str__
Пример #6
0
    def place_order(self,
                    pair: str,
                    is_sell: bool,
                    price: float,
                    amount: float,
                    limit_fee=None,
                    fill_or_kill=False) -> str:
        assert (isinstance(pair, str))
        assert (isinstance(is_sell, bool))
        assert (isinstance(price, float))
        assert (isinstance(amount, float))

        side = 'SELL' if is_sell else 'BUY'

        limit_fee = Decimal(0.01) if not limit_fee else round(
            Decimal(limit_fee.__float__()), 2)

        self.logger.info(f"Placing order ({side}, amount {amount} of {pair},"
                         f" price {price})...")

        tick_size = abs(
            Decimal(
                self.market_info[pair]['minimumTickSize']).as_tuple().exponent)
        # As market_id is used for amount, use baseCurrency instead of quoteCurrency
        market_id = self.market_info[pair]['baseCurrency']['soloMarketId']
        # Convert tokens with different decimals to standard wei units
        decimal_exponent = (
            18 - int(self.market_info[pair]['quoteCurrency']['decimals'])) * -1

        unformatted_price = price
        unformatted_amount = amount
        price = round(Decimal(unformatted_price * (10**decimal_exponent)),
                      tick_size)
        amount = utils.token_to_wei(amount, market_id)

        created_order = self.client.place_order(
            market=pair,  # structured as <MAJOR>-<Minor>
            side=side,
            price=price,
            amount=amount,
            limitFee=limit_fee,
            fillOrKill=fill_or_kill,
            postOnly=False)['order']
        order_id = created_order['id']

        self.logger.info(
            f"Placed {side} order #{order_id} with amount {unformatted_amount}, at price {unformatted_price}"
        )
        return order_id
Пример #7
0
def drange(start, end, num_interval):
    """
    evenly divided start~end space into num_interval pieces
    """
    assert start < end
    assert isinstance(num_interval, int)

    from decimal import Decimal, getcontext

    getcontext().prec = 6

    stepsize = Decimal(end - start) / Decimal(num_interval)

    increment = Decimal(start)
    res = list()
    for i in xrange(num_interval):
        res.append(increment.__float__())
        increment += stepsize

    return res
Пример #8
0
def start():
    ram_ticker = {}
    ram_price = {}
    while True:
        ticker = get_tikcer(symbol)
        if ticker == ram_ticker:
            continue
        price = ticker[0]
        ram_ticker = ticker
        t1 = time.time()
        data = fcoin.get_market_depth("L20", symbol)['data']
        bids = data['bids']
        asks = data['asks']
        bids_depth = 0
        asks_depth = 0
        buy_price = Decimal(0)
        sell_price = Decimal(0)
        for i in range(len(bids)):
            if i % 2 == 1:
                bids_depth += bids[i]
                if bids_depth > Decimal(buy_depth):
                    buy_price = Decimal(bids[i - 1]) + min_price_diff
                    break
        for i in range(len(asks)):
            if i % 2 == 1:
                asks_depth += asks[i]
                if asks_depth > Decimal(sell_depth):
                    sell_price = Decimal(asks[i - 1]) - min_price_diff
                    break
        if buy_price == 0:
            buy_price = Decimal(bids[0])
        if sell_price == 0:
            sell_price = Decimal(asks[0])
        if sell_price - buy_price <= min_price_diff:
            diff = round(Decimal(price) / 100, price_decimal)
            buy_price -= diff
            sell_price += diff
        if buy_price == asks[0]:
            buy_price = bids[0]
        if sell_price == bids[0]:
            sell_price = asks[0]
        local_price = {buy_price, sell_price}
        if ram_price == local_price:
            continue
        ram_price = local_price
        cancel_pending_orders(symbol)
        balances = fcoin.get_balance()['data']
        buy_price = round(buy_price, price_decimal)
        sell_price = round(sell_price, price_decimal)
        amount_buy = round(
            Decimal(get_balance(balances, quote_currency)) / buy_price,
            amount_decimal)
        amount_sell = round(Decimal(get_balance(balances, base_currency)),
                            amount_decimal)
        if amount_buy > 0.02:
            fcoin.buy(symbol, buy_price.__float__(), amount_buy.__float__())
        if amount_sell > 0.02:
            fcoin.sell(symbol, sell_price.__float__(), amount_sell.__float__())
        print("price", price, "buy_depth", bids_depth, "ticker_buy_price",
              bids[0], "sell_depth", asks_depth, "ticker_sell_price", asks[0])
        print("buy_price", buy_price, "buy_amount", amount_buy, "sell_price",
              sell_price, "sell_amount", amount_sell)
        t2 = time.time()
        print("耗时", t2 - t1, "s")
Пример #9
0
 def _decimal_to_python(decimal_number: Decimal) -> float or int:
     decimal_float = decimal_number.__float__()
     return decimal_float if decimal_float.is_integer() is not True else int(decimal_float)
Пример #10
0
		results[i][j] = c
		clr = mycmap.to_rgba(c)
		draw2.point((i,j),(int(255*c)))
		print((i, j), (int(255 * clr[0]), int(255 * clr[1]), int(255 * clr[2])))
		draw.point((i, j), (int(255*clr[0]), int(255*clr[1]), int(255*clr[2])))

print('Saving')
image.save(filename+".bmp", "BMP")
image_grey.save(filename+"_grey.bmp", "BMP")
del draw, draw2
print(datetime.datetime.now().time())
if drawing:
	print('Started graphing')
	plt.gca().set_aspect('equal', adjustable='box')
	plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=1.0)
	plt.xlim([center[0].__float__()-dimension.__float__()/2, center[0].__float__()+dimension.__float__()/2])
	plt.ylim([center[1].__float__()-dimension.__float__()/2, center[1].__float__()+dimension.__float__()/2])
	plt.scatter(np.array([np.array([i] * resolution) for i in np.arange(-dimension / 2+center[0], dimension / 2+center[0], dimension / resolution)]).flatten(),
				np.array([np.array([i] * resolution) for i in np.arange(-dimension / 2+center[1], dimension / 2+center[1], dimension / resolution)]).T.flatten(),
				c=results.flatten(),marker=',', picker=True, cmap=cmp)
	plt.show()


'''numpy.zeros(shape=(5,2))
>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)
Пример #11
0
#p ∗ e^−x + q ∗ sin(x) + r ∗ cos(x) + s ∗ tan(x) + t ∗ x^2 + u = 0
equation = lambda x, p, q, r, s, t, u: p * (math.e**-x) + q * math.sin(
    x) + r * math.cos(x) + s * math.tan(x) + t * x * x + u

for R in regex:
    if (len(R) == 6):
        x = Decimal('0.5')
        delta = Decimal('0.1')
        minDelta = Decimal('0.0001')
        achou = False
        r = {}
        #Xs = []
        sinal = 1
        while x <= 1.0:
            result = equation(*([x.__float__()] + R))
            if result > -delta * 10 and result < delta * 10 and delta > minDelta:
                delta /= 10

            if result > -0.001 and result < 0.001:
                r[abs(result)] = x
                #r.append(abs(result))
                #Xs.append(x)
                achou = True
            elif achou and sinal > 0:
                sinal = -1
            elif achou and sinal < 0:
                break
            if not achou:
                x += (delta if result > 0 else -delta)
            else:
Пример #12
0
            break
    return i / color_space


results = np.zeros(shape=(resolution, resolution))
for i in range(resolution):
    for j in range(resolution):
        results[i][j] = get_color(i, j)

print('Started graphing')

fig = plt.figure()
plt.gca().set_aspect('equal', adjustable='box')
plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=1.0)
plt.xlim([
    center[0].__float__() - dimension.__float__() / 2,
    center[0].__float__() + dimension.__float__() / 2
])
plt.ylim([
    center[1].__float__() - dimension.__float__() / 2,
    center[1].__float__() + dimension.__float__() / 2
])
scatter = plt.scatter(
    np.array([
        np.array([i] * resolution)
        for i in np.arange(-dimension / 2 + center[0], dimension / 2 +
                           center[0], dimension / resolution)
    ]).flatten(),
    np.array([
        np.array([i] * resolution)
        for i in np.arange(-dimension / 2 + center[1], dimension / 2 +