示例#1
0
class BTStack(object):
    def __init__(self, pyusb_dev=None):
        if not pyusb_dev:
            pyusb_dev = \
                pyusb_bt_sockets.find_first_bt_adapter_pyusb_device_or_raise()
        self.hci_socket = pyusb_bt_sockets.PyUSBBluetoothHCISocket(pyusb_dev)
        self.hci = HCIThread(self.hci_socket)
        self.cb_thread = CallbackThread()
        self.cb_thread.register_with_rx_thread(self.hci)
        self.is_scannning_enabled = False
        self.connection_mgr = ConnectionManager(
            self.hci, self.cb_thread)
        self.address = None

    def start(self):
        LOG.debug("BTStack start()")

        # During reset, just ignore and eat all packets that might come in:
        ignore_queue = Queue.Queue()
        self.hci.add_packet_queue(lambda packet: True, ignore_queue)
        self.hci.start()
        self.hci.cmd_reset()
        self.hci.remove_packet_queue(ignore_queue)

        self.cb_thread.start()

        self.hci.cmd_set_event_filter_clear_all_filters()
        self.hci.cmd_set_event_mask()
        self.hci.cmd_le_host_supported()

        # "The LE_Read_Buffer_Size command must be issued by the Host before it
        #  sends any data to an LE Controller":
        self.hci.cmd_le_read_buffer_size()

        self.address = self.hci.cmd_read_bd_addr()

    def start_scan(self):
        assert self.is_scannning_enabled is False
        self.hci.cmd_le_scan_params()
        self.hci.cmd_le_scan_enable(True)
        self.is_scannning_enabled = True

    def stop_scan(self):
        assert self.is_scannning_enabled is True
        self.hci.cmd_le_scan_enable(False)
        self.is_scannning_enabled = False

    def connect(self, address):
        return self.connection_mgr.connect(address)

    def disconnect(self, connection):
        self.connection_mgr.disconnect(connection)

    def quit(self):
        LOG.debug("BTStack quit()")
        self.hci.cmd_reset()
        self.hci.kill()
        self.cb_thread.kill()
示例#2
0
class BTStack(object):
    def __init__(self, pyusb_dev=None):
        if not pyusb_dev:
            pyusb_dev = \
                pyusb_bt_sockets.find_first_bt_adapter_pyusb_device_or_raise()
        self.hci_socket = pyusb_bt_sockets.PyUSBBluetoothHCISocket(pyusb_dev)
        self.hci = HCIThread(self.hci_socket)
        self.cb_thread = CallbackThread()
        self.cb_thread.register_with_rx_thread(self.hci)
        self.is_scannning_enabled = False
        self.connection_mgr = ConnectionManager(self.hci, self.cb_thread)
        self.address = None

    def start(self):
        LOG.debug("BTStack start()")

        # During reset, just ignore and eat all packets that might come in:
        ignore_queue = Queue.Queue()
        self.hci.add_packet_queue(lambda packet: True, ignore_queue)
        self.hci.start()
        self.hci.cmd_reset()
        self.hci.remove_packet_queue(ignore_queue)

        self.cb_thread.start()

        self.hci.cmd_set_event_filter_clear_all_filters()
        self.hci.cmd_set_event_mask()
        self.hci.cmd_le_host_supported()

        # "The LE_Read_Buffer_Size command must be issued by the Host before it
        #  sends any data to an LE Controller":
        self.hci.cmd_le_read_buffer_size()

        self.address = self.hci.cmd_read_bd_addr()

    def start_scan(self):
        assert self.is_scannning_enabled is False
        self.hci.cmd_le_scan_params()
        self.hci.cmd_le_scan_enable(True)
        self.is_scannning_enabled = True

    def stop_scan(self):
        assert self.is_scannning_enabled is True
        self.hci.cmd_le_scan_enable(False)
        self.is_scannning_enabled = False

    def connect(self, address):
        return self.connection_mgr.connect(address)

    def disconnect(self, connection):
        self.connection_mgr.disconnect(connection)

    def quit(self):
        LOG.debug("BTStack quit()")
        self.hci.cmd_reset()
        self.hci.kill()
        self.cb_thread.kill()
示例#3
0
 def __init__(self, pyusb_dev=None):
     if not pyusb_dev:
         pyusb_dev = \
             pyusb_bt_sockets.find_first_bt_adapter_pyusb_device_or_raise()
     self.hci_socket = pyusb_bt_sockets.PyUSBBluetoothHCISocket(pyusb_dev)
     self.hci = HCIThread(self.hci_socket)
     self.cb_thread = CallbackThread()
     self.cb_thread.register_with_rx_thread(self.hci)
     self.is_scannning_enabled = False
     self.connection_mgr = ConnectionManager(self.hci, self.cb_thread)
     self.address = None
示例#4
0
 def round_quantity_1(self, asset) -> float:
     fee_percent = 0.9995
     min_qty, max_qty, step_size = Account.get_lot_size_info(
         pair=self.trade_pair)
     balance = Account.get_balance(client=ConnectionManager.get_client(),
                                   asset=asset)['free']
     trades = ConnectionManager.get_client().get_recent_trades(
         symbol=self.trade_pair)
     quantity = (float(balance)) * fee_percent
     precision = int(round(-math.log(step_size, 10), 0))
     return round(quantity, precision)
示例#5
0
    def start_session(self, asset: str, quote: str):
        self.__asset: str = asset
        self.__quote_currency: str = quote
        self.__trade_pair = str(self.__asset + self.__quote_currency)
        self.set_logger(self.__trade_pair)
        if config.MODE_WATCH_ONLY:
            self.__trade_session = None
        else:
            balance = float(
                Account.get_balance(ConnectionManager.get_client(),
                                    self.__quote_currency)['free'])
            self.__trade_session = TradeSession(self.__asset,
                                                self.__quote_currency,
                                                initial_buy=balance)
            self.__strategy.on_start(client=ConnectionManager.get_client(),
                                     trade=self.__trade_session)

        ConnectionManager.subscribe_to_stream(self.__trade_pair,
                                              on_event_fn=self.handle_event)
示例#6
0
    def __init__(self, cm=None, client_id=None, prefix="riak",
                 mapred_prefix="mapred"):
        if cm is None:
            cm = ConnectionManager.get_http_cm()
        self._connections = cm
        self._prefix = prefix
        self._mapred_prefix = mapred_prefix

        self.solr = self.HttpSolrTransport(self)

        self.client_id = client_id or self.random_client_id()
示例#7
0
 def __init__(self, pyusb_dev=None):
     if not pyusb_dev:
         pyusb_dev = \
             pyusb_bt_sockets.find_first_bt_adapter_pyusb_device_or_raise()
     self.hci_socket = pyusb_bt_sockets.PyUSBBluetoothHCISocket(pyusb_dev)
     self.hci = HCIThread(self.hci_socket)
     self.cb_thread = CallbackThread()
     self.cb_thread.register_with_rx_thread(self.hci)
     self.is_scannning_enabled = False
     self.connection_mgr = ConnectionManager(
         self.hci, self.cb_thread)
     self.address = None
示例#8
0
    def execute_limit_sell(self, price: float):
        print("> Posting Limit Sell Order")
        client = ConnectionManager.get_client()
        qty = self.round_quantity_1(asset=self.asset)

        order = client.order_limit_sell(symbol=self.trade_pair,
                                        quantity=qty,
                                        price="{:.8f}".format(price))
        print(order)
        print(
            "> Limit Sell Posted @ {} (MarketPrice) Executed for '{}'.".format(
                price, self.trade_pair))
示例#9
0
    def __init__(self):
        self.__trade_pair = None
        self.__trade_session = None
        self.__quote_currency = None
        self.__asset = None
        self.__logger = None
        self.__strategy = PCent()

        client = ConnectionManager.get_client()
        Account.get_balance(client, "BTC")
        # Account.get_balance(client, "USDT")
        Account.load_trade_pair_info(client)
        Account.print_balances()
示例#10
0
    def connect(self, host, port, bucket, user, pwd, handler):
        # Runs open connection on each node and sends control commands
        self.lock.acquire()
        if self.connection is not None:
            raise ConnectedException("Connection already established")

        self.rest = RestClient(host, port, user, pwd)
        self.rest.update()
        cluster_config = self.rest.get_nodes()
        bucket_config = self.rest.get_bucket(bucket)
        bucket_password = bucket_config['password'].encode('ascii')

        self.connection = ConnectionManager(handler)
        self.connection.connect(cluster_config, bucket_config)

        # Send the sasl auth message
        latch = CountdownLatch(len(self.rest.get_nodes()))
        op = SaslPlain(bucket, bucket_password, latch)
        self.connection.add_operation_all(op)
        # Todo: Check the value of get_result

        # Send the open connection message
        name = 'py_dcp:' + str(uuid.uuid4())[0:7] + str(uuid.uuid4())[0:7]
        latch = CountdownLatch(len(self.rest.get_nodes()))
        op = OpenConnection(FLAG_OPEN_PRODUCER, name, latch)
        self.connection.add_operation_all(op)
        # Todo: Check the value of get_result
        op.get_result()

        # Send the set priority control message
        latch = CountdownLatch(len(self.rest.get_nodes()))
        op = Control("set_priority", self.priority, latch)
        self.connection.add_operation_all(op)
        # Todo: Check the value of get_result

        # Todo: Add the ability to send control messages

        self.lock.release()
示例#11
0
    def execute_market_sell(self, quantity_percent: float):
        print("> Posting Sell Order")
        sell_qty = float(self.remaining_quantity * (quantity_percent / 100))

        order = ConnectionManager.get_client().order_market_sell(
            symbol=self.trade_pair, quantity=sell_qty)

        self.exit_prices.append(order['price'])
        self.remaining_quantity = float(self.remaining_quantity) - float(
            order['executedQty'])
        self.my_trades.append(order)
        print("> Trade Confirmed : Sell @ {} (MarketPrice) Executed for '{}'.".
              format(order['price'], self.trade_pair))
        print("> Remaining Quantity: {}".format(self.remaining_quantity))
示例#12
0
    def __execute_market_buy(self, quote_quantity: float) -> (float, float):
        print("> Posting Buy Order")
        client = ConnectionManager.get_client()
        qty = self.round_quantity()

        order = client.order_market_buy(symbol=self.trade_pair, quantity=qty)
        print(order)

        # avg_entry_price = dict(functools.reduce(operator.add, map(collections.Counter, order['fills'])))['price']
        avg_entry_price = order['fills'][0]['price']
        qty = order['fills'][0]["qty"]

        print("> Trade Confirmed : Buy @ {} (MarketPrice) Executed for '{}'.".
              format(order['price'], self.trade_pair))
        self.my_trades.append(order)
        return float(avg_entry_price), float(qty)
示例#13
0
class DcpClient(object):

    def __init__(self, priority="medium"):
        self.lock = threading.Lock()
        self.rest = None
        self.connection = None
        self.priority = priority

    # Returns true is connections are successful
    def connect(self, host, port, bucket, user, pwd, handler):
        # Runs open connection on each node and sends control commands
        self.lock.acquire()
        if self.connection is not None:
            raise ConnectedException("Connection already established")

        self.rest = RestClient(host, port, user, pwd)
        self.rest.update()
        cluster_config = self.rest.get_nodes()
        bucket_config = self.rest.get_bucket(bucket)
        bucket_password = bucket_config['password'].encode('ascii')

        self.connection = ConnectionManager(handler)
        self.connection.connect(cluster_config, bucket_config)

        # Send the sasl auth message
        latch = CountdownLatch(len(self.rest.get_nodes()))
        op = SaslPlain(bucket, bucket_password, latch)
        self.connection.add_operation_all(op)
        # Todo: Check the value of get_result

        # Send the open connection message
        name = 'py_dcp:' + str(uuid.uuid4())[0:7] + str(uuid.uuid4())[0:7]
        latch = CountdownLatch(len(self.rest.get_nodes()))
        op = OpenConnection(FLAG_OPEN_PRODUCER, name, latch)
        self.connection.add_operation_all(op)
        # Todo: Check the value of get_result
        op.get_result()

        # Send the set priority control message
        latch = CountdownLatch(len(self.rest.get_nodes()))
        op = Control("set_priority", self.priority, latch)
        self.connection.add_operation_all(op)
        # Todo: Check the value of get_result

        # Todo: Add the ability to send control messages

        self.lock.release()

    # Returns true if the stream is successfully created
    def add_stream(self, vbucket, flags, start_seqno, end_seqno, vb_uuid,
                   snap_start, snap_end):
        self.lock.acquire()
        if self.connection is None:
            raise ConnectedException("Not connected")

        latch = CountdownLatch()
        op = StreamRequest(vbucket, flags, start_seqno, end_seqno, vb_uuid,
                           snap_start, snap_end, latch)
        self.connection.add_operation(op, vbucket)
        ret = op.get_result()

        self.lock.release()
        return ret

    # Returns true if the stream is closed successfully
    def close_stream(self):
        self.lock.acquire()
        if self.connection is None:
            raise ConnectedException("Not connected")
        raise NotImplementedError("Not impemented yet")
        self.lock.release()

    def close(self):
        self.lock.acquire()
        self.connection.close()
        self.client = None
        self.nodes = None
        self.buckets = None
        self.connection = None
        self.lock.release()
示例#14
0
    def _createConnection(self, info):
        connection = ConnectionManager(info)
        connection.Connect()

        return connection