本文整理汇总了Python中bintrees.FastRBTree.insert方法的典型用法代码示例。如果您正苦于以下问题:Python FastRBTree.insert方法的具体用法?Python FastRBTree.insert怎么用?Python FastRBTree.insert使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bintrees.FastRBTree
的用法示例。
在下文中一共展示了FastRBTree.insert方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Tree
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
class Tree(object):
def __init__(self):
self.priceTree = FastRBTree()
self.volume = 0
self.priceMap = {} # Map from price -> orderList object
self.orderMap = {} # Order ID to Order object
def __len__(self):
return len(self.orderMap)
def getPrice(self, price):
return self.priceMap[price]
def getOrder(self, idNum):
return self.orderMap[idNum]
def createPrice(self, price):
newList = OrderList()
self.priceTree.insert(price, newList)
self.priceMap[price] = newList
def removePrice(self, price):
self.priceTree.remove(price)
del self.priceMap[price]
def priceExists(self, price):
return price in self.priceMap
def orderExists(self, idNum):
return idNum in self.orderMap
def insertTick(self, tick):
if tick.price not in self.priceMap:
self.createPrice(tick.price)
order = Order(tick, self.priceMap[tick.price])
self.priceMap[order.price].appendOrder(order)
self.orderMap[order.idNum] = order
self.volume += order.qty
def updateOrder(self, tick):
order = self.orderMap[tick.idNum]
originalVolume = order.qty
if tick.price != order.price:
# Price changed
orderList = self.priceMap[order.price]
orderList.removeOrder(order)
if len(orderList) == 0:
removePrice(order.price)
self.insertTick(tick)
else:
# Quantity changed
order.updateQty(tick.qty,tick.price)
self.volume += order.qty - originalVolume
def removeOrderById(self, idNum):
order = self.orderMap[idNum]
self.volume -= order.qty
order.orderList.removeOrder(order)
if len(order.orderList) == 0:
self.removePrice(order.price)
del self.orderMap[idNum]
def max(self):
return min(self.priceTree)
def min(self):
return max(self.priceTree)
示例2: Tree
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
class Tree(object):
def __init__(self):
self.price_tree = FastRBTree()
self.price_map = {} # Map from price -> order_list object
self.order_map = {} # Order ID to Order object
self.received_orders = {}
def receive(self, order_id, size):
self.received_orders[order_id] = size
def create_price(self, price):
new_list = OrderList()
self.price_tree.insert(price, new_list)
self.price_map[price] = new_list
def remove_price(self, price):
self.price_tree.remove(price)
del self.price_map[price]
def insert_order(self, order_id, size, price, initial=False):
if not initial:
del self.received_orders[order_id]
if price not in self.price_map:
self.create_price(price)
order = Order(order_id, size, price, self.price_map[price])
self.price_map[order.price].append_order(order)
self.order_map[order.order_id] = order
def match(self, maker_order_id, size):
order = self.order_map[maker_order_id]
original_size = order.size
new_size = original_size - size
order.update_size(new_size)
def change(self, order_id, new_size):
order = self.order_map[order_id]
order.update_size(new_size)
def remove_order(self, order_id):
if order_id in self.order_map:
order = self.order_map[order_id]
order.order_list.remove_order(order)
if len(order.order_list) == 0:
self.remove_price(order.price)
del self.order_map[order_id]
else:
del self.received_orders[order_id]
示例3: Tree
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
class Tree(object):
def __init__(self):
self.price_tree = FastRBTree()
self.price_map = {}
self.order_map = {}
self.received_orders = {}
def receive(self, order_id, size):
self.received_orders[order_id] = size
def create_price(self, price):
new_list = []
self.price_tree.insert(price, new_list)
self.price_map[price] = new_list
def remove_price(self, price):
self.price_tree.remove(price)
del self.price_map[price]
def insert_order(self, order_id, size, price, initial=False):
if not initial:
del self.received_orders[order_id]
if price not in self.price_map:
self.create_price(price)
order = {'order_id': order_id, 'size': size, 'price': price, 'price_map': self.price_map[price]}
self.price_map[price].append(order)
self.order_map[order_id] = order
def match(self, maker_order_id, match_size):
order = self.order_map[maker_order_id]
original_size = order['size']
new_size = original_size - match_size
order['size'] = new_size
def change(self, order_id, new_size):
order = self.order_map[order_id]
order['size'] = new_size
def remove_order(self, order_id):
if order_id in self.order_map:
order = self.order_map[order_id]
self.price_map[order['price']] = [o for o in self.price_map[order['price']] if o['order_id'] != order_id]
if not self.price_map[order['price']]:
self.remove_price(order['price'])
del self.order_map[order_id]
else:
del self.received_orders[order_id]
示例4: OrderTree
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
class OrderTree(object):
def __init__(self):
self.price_tree = FastRBTree()
self.price_map = {}
self.min_price = None
self.max_price = None
def insert_price(self, price, amount):
self.price_tree.insert(price, amount)
self.price_map[price] = amount
if self.max_price == None or price > self.max_price:
self.max_price = price
if self.min_price == None or price < self.min_price:
self.min_price = price
def update_price(self, price, amount):
self.price_tree.insert(price, amount) #updates if key exists
self.price_map[price] = amount
def remove_price(self, price):
self.price_tree.remove(price)
del self.price_map[price]
if self.max_price == price:
try:
self.max_price = max(self.price_tree)
except ValueError:
self.max_price = None
if self.min_price == price:
try:
self.min_price = min(self.price_tree)
except ValueError:
self.min_price = None
def price_exists(self, price):
return price in self.price_map
def max(self):
return self.max_price
def min(self):
return self.min_price
示例5: __init__
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
class Hyperedge:
def __init__(self, hyperkey, col, hlabel):
self.hyperkey = hyperkey
self.col = col
self._alerts = Tree()
self.insert_alert(hlabel, 1)
self.nalerts = 1
def get_alert(self, key):
return self._alerts.get(key)
def insert_alert(self, alert_key, count):
self._alerts.insert(alert_key, count)
def foreach_alert(self, func):
self._alerts.foreach(func)
def pop_alert(self, key):
return self._alerts.pop(key)
示例6: Tree
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
class Tree(object):
def __init__(self):
self.price_tree = FastRBTree()
self.volume = 0
self.price_map = {} # Map from price -> order_list object
self.order_map = {} # Order ID to Order object
self.min_price = None
self.max_price = None
def __len__(self):
return len(self.order_map)
def get_price(self, price):
return self.price_map[price]
def get_order(self, id_num):
return self.order_map[id_num]
def create_price(self, price):
new_list = OrderList()
self.price_tree.insert(price, new_list)
self.price_map[price] = new_list
if self.max_price == None or price > self.max_price:
self.max_price = price
if self.min_price == None or price < self.min_price:
self.min_price = price
def remove_price(self, price):
self.price_tree.remove(price)
del self.price_map[price]
if self.max_price == price:
try:
self.max_price = max(self.price_tree)
except ValueError:
self.max_price = None
if self.min_price == price:
try:
self.min_price = min(self.price_tree)
except ValueError:
self.min_price = None
def price_exists(self, price):
return price in self.price_map
def order_exists(self, id_num):
return id_num in self.order_map
def insert_tick(self, tick):
if tick.price not in self.price_map:
self.create_price(tick.price)
order = Order(tick, self.price_map[tick.price])
self.price_map[order.price].append_order(order)
self.order_map[order.id_num] = order
self.volume += order.qty
def update_order(self, tick):
order = self.order_map[tick.id_num]
original_volume = order.qty
if tick.price != order.price:
# Price changed
order_list = self.price_map[order.price]
order_list.remove_order(order)
if len(order_list) == 0:
self.remove_price(order.price)
self.insert_tick(tick)
self.volume -= original_volume
else:
# Quantity changed
order.update_qty(tick.qty, tick.price)
self.volume += order.qty - original_volume
def remove_order_by_id(self, id_num):
order = self.order_map[id_num]
self.volume -= order.qty
order.order_list.remove_order(order)
if len(order.order_list) == 0:
self.remove_price(order.price)
del self.order_map[id_num]
def max(self):
return self.max_price
def min(self):
return self.min_price
示例7: TDigest
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
class TDigest(object):
def __init__(self, delta=0.01, K=25):
self.C = RBTree()
self.n = 0
self.delta = delta
self.K = K
def __add__(self, other_digest):
C1 = list(self.C.values())
C2 = list(other_digest.C.values())
shuffle(C1)
shuffle(C2)
data = C1 + C2
new_digest = TDigest(self.delta, self.K)
for c in data:
new_digest.update(c.mean, c.count)
return new_digest
def __len__(self):
return len(self.C)
def __repr__(self):
return """<T-Digest: n=%d, centroids=%d>""" % (self.n, len(self))
def _add_centroid(self, centroid):
if centroid.mean not in self.C:
self.C.insert(centroid.mean, centroid)
else:
self.C[centroid.mean].update(centroid.mean, centroid.count)
def _compute_centroid_quantile(self, centroid):
denom = self.n
cumulative_sum = sum(
c_i.count for c_i in self.C.value_slice(-float('Inf'), centroid.mean))
return (centroid.count / 2. + cumulative_sum) / denom
def _update_centroid(self, centroid, x, w):
self.C.pop(centroid.mean)
centroid.update(x, w)
self._add_centroid(centroid)
def _find_closest_centroids(self, x):
try:
ceil_key = self.C.ceiling_key(x)
except KeyError:
floor_key = self.C.floor_key(x)
return [self.C[floor_key]]
try:
floor_key = self.C.floor_key(x)
except KeyError:
ceil_key = self.C.ceiling_key(x)
return [self.C[ceil_key]]
if abs(floor_key - x) < abs(ceil_key - x):
return [self.C[floor_key]]
elif abs(floor_key - x) == abs(ceil_key - x) and (ceil_key != floor_key):
return [self.C[ceil_key], self.C[floor_key]]
else:
return [self.C[ceil_key]]
def _theshold(self, q):
return 4 * self.n * self.delta * q * (1 - q)
def update(self, x, w=1):
"""
Update the t-digest with value x and weight w.
"""
self.n += w
if len(self) == 0:
self._add_centroid(Centroid(x, w))
return
S = self._find_closest_centroids(x)
while len(S) != 0 and w > 0:
j = choice(list(range(len(S))))
c_j = S[j]
q = self._compute_centroid_quantile(c_j)
# This filters the out centroids that do not satisfy the second part
# of the definition of S. See original paper by Dunning.
if c_j.count + w > self._theshold(q):
S.pop(j)
continue
delta_w = min(self._theshold(q) - c_j.count, w)
self._update_centroid(c_j, x, delta_w)
w -= delta_w
S.pop(j)
if w > 0:
self._add_centroid(Centroid(x, w))
if len(self) > self.K / self.delta:
#.........这里部分代码省略.........
示例8: BookSide
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
#.........这里部分代码省略.........
# return that the update was done
return True
def _canc_expr_filled_order(self, order_obj, i_old_id, f_old_pr, i_old_q):
'''
Update price_tree when passed canceled, expried or filled orders
:param order_obj: Order Object. The last order in the file
:param i_old_id: integer. Old id of the order_obj
:param f_old_pr: float. Old price of the order_obj
:param i_old_q: integer. Old qty of the order_obj
'''
this_price = self.price_tree.get(f_old_pr)
if this_price.delete(i_old_id, i_old_q):
self.price_tree.remove(f_old_pr)
# remove from order map
return False
def _replaced_order(self, order_obj, i_old_id, f_old_pr, i_old_q):
'''
Update price_tree when passed replaced orders
:param order_obj: Order Object. The last order in the file
:param i_old_id: integer. Old id of the order_obj
:param f_old_pr: float. Old price of the order_obj
:param i_old_q: integer. Old qty of the order_obj
'''
# remove from the old price
this_price = self.price_tree.get(f_old_pr)
if this_price.delete(i_old_id, i_old_q):
self.price_tree.remove(f_old_pr)
# insert in the new price
f_price = order_obj['order_price']
if not self.price_tree.get(f_price):
self.price_tree.insert(f_price, PriceLevel(f_price))
# insert the order in the due price
this_price = self.price_tree.get(f_price)
this_price.add(order_obj)
return True
def _partially_filled(self, order_obj, i_old_id, f_old_pr, i_old_q):
'''
Update price_tree when passed partially filled orders
:param order_obj: Order Object. The last order in the file
:param i_old_id: integer. Old id of the order_obj
:param f_old_pr: float. Old price of the order_obj
:param i_old_q: integer. Old qty of the order_obj
'''
# delete old price, if it is needed
this_price = self.price_tree.get(f_old_pr)
if this_price.delete(i_old_id, i_old_q):
self.price_tree.remove(f_old_pr)
# add/modify order
# insert in the new price
f_price = order_obj['order_price']
if not self.price_tree.get(f_price):
self.price_tree.insert(f_price, PriceLevel(f_price))
this_price = self.price_tree.get(f_price)
this_price.add(order_obj)
return True
def _new_order(self, order_obj):
'''
Update price_tree when passed new orders
:param order_obj: Order Object. The last order in the file
'''
示例9: PriceLevel
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
class PriceLevel(object):
'''
A representation of a Price level in the book
'''
def __init__(self, f_price):
'''
A representation of a PriceLevel object
'''
self.f_price = f_price
self.i_qty = 0
self.order_tree = FastRBTree()
def add(self, order_aux):
'''
Insert the information in the tree using the info in order_aux. Return
is should delete the Price level or not
:param order_aux: Order Object. The Order message to be updated
'''
# check if the order_aux price is the same of the self
s_status = order_aux['order_status']
if order_aux['order_price'] != self.f_price:
raise DifferentPriceException
elif s_status in ['New', 'Replaced', 'Partially Filled']:
self.order_tree.insert(order_aux.main_id, order_aux)
self.i_qty += int(order_aux['total_qty_order'])
# check if there is no object in the updated tree (should be deleted)
return self.order_tree.count == 0
def delete(self, i_last_id, i_old_qty):
'''
Delete the information in the tree using the info in order_aux. Return
is should delete the Price level or not
:param i_last_id: Integer. The previous secondary order id
:param i_old_qty: Integer. The previous order qty
'''
# check if the order_aux price is the same of the self
try:
self.order_tree.remove(i_last_id)
self.i_qty -= i_old_qty
except KeyError:
raise DifferentPriceException
# check if there is no object in the updated tree (should be deleted)
return self.order_tree.count == 0
def __str__(self):
'''
Return the name of the PriceLevel
'''
return '{:,.0f}'.format(self.i_qty)
def __repr__(self):
'''
Return the name of the PriceLevel
'''
return '{:,.0f}'.format(self.i_qty)
def __eq__(self, other):
'''
Return if a PriceLevel has equal price from the other
:param other: PriceLevel object. PriceLevel to be compared
'''
# just to make sure that there is no floating point discrepance
f_aux = other
if not isinstance(other, float):
f_aux = other.f_price
return abs(self.f_price - f_aux) < 1e-4
def __gt__(self, other):
'''
Return if a PriceLevel has a gerater price from the other.
Bintrees uses that to compare nodes
:param other: PriceLevel object. PriceLevel to be compared
'''
# just to make sure that there is no floating point discrepance
f_aux = other
if not isinstance(other, float):
f_aux = other.f_price
return (f_aux - self.f_price) > 1e-4
def __lt__(self, other):
'''
Return if a Order has smaller order_id from the other. Bintrees uses
that to compare nodes
:param other: Order object. Order to be compared
'''
f_aux = other
if not isinstance(other, float):
f_aux = other.f_price
return (f_aux - self.f_price) < -1e-4
def __ne__(self, other):
'''
Return if a Order has different order_id from the other
:param other: Order object. Order to be compared
'''
return not self.__eq__(other)
示例10: range
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
for x in range(0, 3000):
alert = []
for y in range(0, 6):
alert.append(repr(randint(0, 8 - 1)) + "test")
for c in hcombinations:
label = []
key = alert[:]
for x in range(2):
key[c[x]] = "*"
label.append(alert[c[x]])
hyperkey = tuple(key)
hlabel = tuple(label)
if hyperkey in hyper_dict:
hyper_dict[hyperkey].nalerts += 1
result = hyper_dict[hyperkey].get_alert(hlabel)
if result is not None:
hyper_dict[hyperkey].insert_alert(hlabel, result + 1)
else:
hyper_dict[hyperkey].insert_alert(hlabel, 1)
else:
hyper_dict[hyperkey] = Hyperedge(key, c, hlabel)
for hyperedge in hyper_dict.values():
hypersize_list.insert((hyperedge.nalerts, hyperedge.hyperkey), hyperedge)
while not hypersize_list.is_empty():
(key, hyperedge) = hypersize_list.pop_max()
hyperedge.foreach_alert(treeloop)
print("Completed iteration %d of 10" % z)
示例11: OrderQueue
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
class OrderQueue(object):
"""
"""
def __init__(self):
self.Orders = FastRBTree()
self.totalAmount = 0.0
def append(self,order):
k = order.timestamp
self.Orders.insert(k,order)
self.totalAmount += self.Orders[k].amount
def count(self):
return self.Orders.count
def min_item(self):
return self.Orders.min_item()
def eat(self,amount):
"""
use this only if amount <= self.amount
return OrderToPop,RestAmount
"""
current_amount = amount
to_pop_orders = []
while self.totalAmount>0 and current_amount>0:
if not self.Orders or self.Orders.count==0:
#print "amount:%.4f" % self.totalAmount
self.totalAmount = 0.0
return []
min_item = self.Orders.min_item()
min_i = min_item[1]
# 1.enough
# 2.not enough
if min_i.amount <= current_amount:
current_amount -= min_i.amount
self.totalAmount -= min_i.amount
to_pop_orders.append(self.Orders.pop_min()[1])
continue
# this is a hard case , need to take care of
# first we split the order , take amount from current order
# and make
elif min_i.amount > current_amount:
new_order = min_i.copy()
new_order.amount = current_amount
to_pop_orders.append(new_order)
min_i.amount -= current_amount
self.totalAmount -= current_amount
current_amount = 0
break
# return:
# 1.orders
# 2.amount to trade
# 3.amount left
return to_pop_orders
def remove(self,order):
k = order.timestamp
self.totalAmount -= self.Orders[k].amount
self.Orders.remove(k)
def get_price_depth(self):
return self.totalAmount
def is_empty(self):
return self.Orders.count == 0
示例12: BookSide
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
#.........这里部分代码省略.........
def _canc_expr_filled_order(self, order_obj, i_old_id, f_old_pr, i_old_q):
'''
Update price_tree when passed canceled, expried or filled orders
:param order_obj: Order Object. The last order in the file
:param i_old_id: integer. Old id of the order_obj
:param f_old_pr: float. Old price of the order_obj
:param i_old_q: integer. Old qty of the order_obj
'''
this_price = self.price_tree.get(f_old_pr)
if this_price.delete(i_old_id, i_old_q):
self.price_tree.remove(f_old_pr)
# remove from order map
return False
def _replaced_order(self, order_obj, i_old_id, f_old_pr, i_old_q):
'''
Update price_tree when passed replaced orders
:param order_obj: Order Object. The last order in the file
:param i_old_id: integer. Old id of the order_obj
:param f_old_pr: float. Old price of the order_obj
:param i_old_q: integer. Old qty of the order_obj
'''
# remove from the old price
this_price = self.price_tree.get(f_old_pr)
if this_price.delete(i_old_id, i_old_q):
self.price_tree.remove(f_old_pr)
# insert in the new price
f_price = order_obj['order_price']
if not self.price_tree.get(f_price):
self.price_tree.insert(f_price, PriceLevel(f_price))
# insert the order in the due price
this_price = self.price_tree.get(f_price)
this_price.add(order_obj)
return True
def _partially_filled(self, order_obj, i_old_id, f_old_pr, i_old_q):
'''
Update price_tree when passed partially filled orders
:param order_obj: Order Object. The last order in the file
:param i_old_id: integer. Old id of the order_obj
:param f_old_pr: float. Old price of the order_obj
:param i_old_q: integer. Old qty of the order_obj
'''
# delete old price, if it is needed
this_price = self.price_tree.get(f_old_pr)
if this_price.delete(i_old_id, i_old_q):
self.price_tree.remove(f_old_pr)
# add/modify order
# insert in the new price
f_price = order_obj['order_price']
if not self.price_tree.get(f_price):
self.price_tree.insert(f_price, PriceLevel(f_price))
this_price = self.price_tree.get(f_price)
this_price.add(order_obj)
return True
def _new_order(self, order_obj):
'''
Update price_tree when passed new orders
示例13: BookSide
# 需要导入模块: from bintrees import FastRBTree [as 别名]
# 或者: from bintrees.FastRBTree import insert [as 别名]
#.........这里部分代码省略.........
'''
Update price_tree when passed canceled, expried or filled orders
:param order_obj: Order Object. The last order in the file
:param i_old_id: integer. Old id of the order_obj
:param f_old_pr: float. Old price of the order_obj
:param i_old_q: integer. Old qty of the order_obj
'''
b_break = False
this_price = self.price_tree.get(f_old_pr)
if this_price.delete(i_old_id, i_old_q):
self.price_tree.remove(f_old_pr)
# remove from order map
if b_break:
raise NotImplementedError
return False
def _replaced_order(self, order_obj, i_old_id, f_old_pr, i_old_q):
'''
Update price_tree when passed replaced orders
:param order_obj: Order Object. The last order in the file
:param i_old_id: integer. Old id of the order_obj
:param f_old_pr: float. Old price of the order_obj
:param i_old_q: integer. Old qty of the order_obj
'''
# remove from the old price
this_price = self.price_tree.get(f_old_pr)
if this_price.delete(i_old_id, i_old_q):
self.price_tree.remove(f_old_pr)
# insert in the new price
f_price = order_obj['order_price']
if not self.price_tree.get(f_price):
self.price_tree.insert(f_price, PriceLevel(f_price))
# insert the order in the due price
this_price = self.price_tree.get(f_price)
this_price.add(order_obj)
return True
def _partially_filled(self, order_obj, i_old_id, f_old_pr, i_old_q):
'''
Update price_tree when passed partially filled orders
:param order_obj: Order Object. The last order in the file
:param i_old_id: integer. Old id of the order_obj
:param f_old_pr: float. Old price of the order_obj
:param i_old_q: integer. Old qty of the order_obj
'''
# delete old price, if it is needed
this_price = self.price_tree.get(f_old_pr)
if this_price.delete(i_old_id, i_old_q):
self.price_tree.remove(f_old_pr)
# add/modify order
# insert in the new price
f_price = order_obj['order_price']
if not self.price_tree.get(f_price):
self.price_tree.insert(f_price, PriceLevel(f_price))
this_price = self.price_tree.get(f_price)
this_price.add(order_obj)
return True
def _new_order(self, order_obj):
'''
Update price_tree when passed new orders