Beispiel #1
0
    def test_rest_authenticate(self):
        now = 1234567890.000
        mock_time_provider = MagicMock()
        mock_time_provider.time.return_value = now

        params = {
            "symbol": "LTCBTC",
            "side": "BUY",
            "type": "LIMIT",
            "timeInForce": "GTC",
            "quantity": 1,
            "price": "0.1",
        }
        full_params = copy(params)

        auth = BinanceAuth(api_key=self._api_key, secret_key=self._secret, time_provider=mock_time_provider)
        request = RESTRequest(method=RESTMethod.GET, params=params, is_auth_required=True)
        configured_request = self.async_run_with_timeout(auth.rest_authenticate(request))

        full_params.update({"timestamp": 1234567890000})
        encoded_params = "&".join([f"{key}={value}" for key, value in full_params.items()])
        expected_signature = hmac.new(
            self._secret.encode("utf-8"),
            encoded_params.encode("utf-8"),
            hashlib.sha256).hexdigest()
        self.assertEqual(now * 1e3, configured_request.params["timestamp"])
        self.assertEqual(expected_signature, configured_request.params["signature"])
        self.assertEqual({"X-MBX-APIKEY": self._api_key}, configured_request.headers)
Beispiel #2
0
 def __init__(self,
              binance_api_key: str,
              binance_api_secret: str,
              trading_pairs: Optional[List[str]] = None,
              trading_required: bool = True,
              domain: str = CONSTANTS.DEFAULT_DOMAIN,
              ):
     self._domain = domain
     self._binance_time_synchronizer = TimeSynchronizer()
     super().__init__()
     self._trading_required = trading_required
     self._auth = BinanceAuth(
         api_key=binance_api_key,
         secret_key=binance_api_secret,
         time_provider=self._binance_time_synchronizer)
     self._throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS)
     self._api_factory = web_utils.build_api_factory(
         throttler=self._throttler,
         time_synchronizer=self._binance_time_synchronizer,
         domain=self._domain,
         auth=self._auth)
     self._rest_assistant = None
     self._order_book_tracker = OrderBookTracker(
         data_source=BinanceAPIOrderBookDataSource(
             trading_pairs=trading_pairs,
             domain=self._domain,
             api_factory=self._api_factory,
             throttler=self._throttler),
         trading_pairs=trading_pairs,
         domain=self._domain)
     self._user_stream_tracker = UserStreamTracker(
         data_source=BinanceAPIUserStreamDataSource(
             auth=self._auth,
             domain=self._domain,
             throttler=self._throttler,
             api_factory=self._api_factory,
             time_synchronizer=self._binance_time_synchronizer))
     self._ev_loop = asyncio.get_event_loop()
     self._poll_notifier = asyncio.Event()
     self._last_timestamp = 0
     self._order_not_found_records = {}  # Dict[client_order_id:str, count:int]
     self._trading_rules = {}  # Dict[trading_pair:str, TradingRule]
     self._trade_fees = {}  # Dict[trading_pair:str, (maker_fee_percent:Decimal, taken_fee_percent:Decimal)]
     self._last_update_trade_fees_timestamp = 0
     self._status_polling_task = None
     self._user_stream_tracker_task = None
     self._user_stream_event_listener_task = None
     self._trading_rules_polling_task = None
     self._last_poll_timestamp = 0
     self._last_trades_poll_binance_timestamp = 0
     self._order_tracker: ClientOrderTracker = ClientOrderTracker(connector=self)
    def setUp(self) -> None:
        super().setUp()
        self.log_records = []
        self.listening_task: Optional[asyncio.Task] = None
        self.mocking_assistant = NetworkMockingAssistant()

        self.throttler = AsyncThrottler(rate_limits=CONSTANTS.RATE_LIMITS)
        self.mock_time_provider = MagicMock()
        self.mock_time_provider.time.return_value = 1000
        self.data_source = BinanceAPIUserStreamDataSource(
            auth=BinanceAuth(api_key="TEST_API_KEY", secret_key="TEST_SECRET", time_provider=self.mock_time_provider),
            domain=self.domain,
            throttler=self.throttler
        )

        self.data_source.logger().setLevel(1)
        self.data_source.logger().addHandler(self)

        self.resume_test_event = asyncio.Event()
    def setUp(self) -> None:
        super().setUp()
        self.log_records = []
        self.listening_task: Optional[asyncio.Task] = None
        self.mocking_assistant = NetworkMockingAssistant()

        self.throttler = AsyncThrottler(rate_limits=CONSTANTS.RATE_LIMITS)
        self.mock_time_provider = MagicMock()
        self.mock_time_provider.time.return_value = 1000
        self.auth = BinanceAuth(api_key="TEST_API_KEY", secret_key="TEST_SECRET", time_provider=self.mock_time_provider)
        self.time_synchronizer = TimeSynchronizer()
        self.time_synchronizer.add_time_offset_ms_sample(0)

        client_config_map = ClientConfigAdapter(ClientConfigMap())
        self.connector = BinanceExchange(
            client_config_map=client_config_map,
            binance_api_key="",
            binance_api_secret="",
            trading_pairs=[],
            trading_required=False,
            domain=self.domain)
        self.connector._web_assistants_factory._auth = self.auth

        self.data_source = BinanceAPIUserStreamDataSource(
            auth=self.auth,
            trading_pairs=[self.trading_pair],
            connector=self.connector,
            api_factory=self.connector._web_assistants_factory,
            domain=self.domain
        )

        self.data_source.logger().setLevel(1)
        self.data_source.logger().addHandler(self)

        self.resume_test_event = asyncio.Event()

        self.connector._set_trading_pair_symbol_map(bidict({self.ex_trading_pair: self.trading_pair}))
Beispiel #5
0
 def authenticator(self):
     return BinanceAuth(api_key=self.api_key,
                        secret_key=self.secret_key,
                        time_provider=self._time_synchronizer)