code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
async def check_price_and_open_position(self): """Check current price and open position if target is reached""" if self.position_opening or self.position_opened: return self.position_opening = True try: # Fetch current pool info to get the latest price ...
Check current price and open position if target is reached
check_price_and_open_position
python
hummingbot/hummingbot
scripts/clmm_manage_position.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/clmm_manage_position.py
Apache-2.0
async def open_position(self): """Open a concentrated liquidity position around the target price""" if self.position_opening or self.position_opened: return self.position_opening = True try: # Get the latest pool price before creating the position aw...
Open a concentrated liquidity position around the target price
open_position
python
hummingbot/hummingbot
scripts/clmm_manage_position.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/clmm_manage_position.py
Apache-2.0
async def monitor_position(self): """Monitor the position and price to determine if position should be closed""" if not self.position_address or self.position_closing: return try: # Fetch current pool info to get the latest price await self.fetch_pool_info() ...
Monitor the position and price to determine if position should be closed
monitor_position
python
hummingbot/hummingbot
scripts/clmm_manage_position.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/clmm_manage_position.py
Apache-2.0
async def poll_transaction(self, signature): """Continuously polls for transaction status until completion or max attempts reached""" if not signature: return False self.logger().info(f"Polling for transaction status: {signature}") # Transaction status codes # -1 = ...
Continuously polls for transaction status until completion or max attempts reached
poll_transaction
python
hummingbot/hummingbot
scripts/clmm_manage_position.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/clmm_manage_position.py
Apache-2.0
async def update_position_info(self): """Fetch the latest position information if we have an open position""" if not self.position_opened or not self.position_info: return try: self.position_info = await self.connectors[self.exchange].get_position_info( t...
Fetch the latest position information if we have an open position
update_position_info
python
hummingbot/hummingbot
scripts/lp_manage_position.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/lp_manage_position.py
Apache-2.0
def _get_price_range_visualization(self, current_price: Decimal, lower_price: Decimal, upper_price: Decimal, width: int = 20) -> str: """Generate ASCII visualization of price range""" if not self.pool_info: return "" # Calculate the price range for visualization price_range ...
Generate ASCII visualization of price range
_get_price_range_visualization
python
hummingbot/hummingbot
scripts/lp_manage_position.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/lp_manage_position.py
Apache-2.0
def format_status(self) -> str: """Format status message for display in Hummingbot""" lines = [] if self.position_opened and self.position_info: lines.append(f"Position: {self.position_info.address} ({self.config.trading_pair}) on {self.exchange}") # Common position inf...
Format status message for display in Hummingbot
format_status
python
hummingbot/hummingbot
scripts/lp_manage_position.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/lp_manage_position.py
Apache-2.0
def on_tick(self): """ Every order delay time the strategy will buy or sell the base asset. It will compute the cumulative order book volume until the spread and buy a percentage of that. The input of the strategy is in quote, and we will convert at initial price to get a target base ...
Every order delay time the strategy will buy or sell the base asset. It will compute the cumulative order book volume until the spread and buy a percentage of that. The input of the strategy is in quote, and we will convert at initial price to get a target base that will be static. ...
on_tick
python
hummingbot/hummingbot
scripts/simple_vwap.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/simple_vwap.py
Apache-2.0
def create_order(self) -> OrderCandidate: """ Retrieves the cumulative volume of the order book until the price spread is reached, then takes a percentage of that to use as order amount. """ # Compute the new price using the max spread allowed mid_price = float(self.vw...
Retrieves the cumulative volume of the order book until the price spread is reached, then takes a percentage of that to use as order amount.
create_order
python
hummingbot/hummingbot
scripts/simple_vwap.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/simple_vwap.py
Apache-2.0
def did_fill_order(self, event: OrderFilledEvent): """ Listens to fill order event to log it and notify the Hummingbot application. """ if event.trading_pair == self.vwap["trading_pair"] and event.trade_type == self.vwap["trade_type"]: self.vwap["volume_remaining"] -= event...
Listens to fill order event to log it and notify the Hummingbot application.
did_fill_order
python
hummingbot/hummingbot
scripts/simple_vwap.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/simple_vwap.py
Apache-2.0
def format_status(self) -> str: """ Returns status of the current strategy on user balances and current active orders. This function is called when status command is issued. Override this function to create custom status display output. """ if not self.ready_to_trade: ...
Returns status of the current strategy on user balances and current active orders. This function is called when status command is issued. Override this function to create custom status display output.
format_status
python
hummingbot/hummingbot
scripts/simple_vwap.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/simple_vwap.py
Apache-2.0
def is_active_maker_order(self, event: OrderFilledEvent): """ Helper function that checks if order is an active order on the maker exchange """ for order in self.get_active_orders(connector_name=self.config.maker_exchange): if order.client_order_id == event.order_id: ...
Helper function that checks if order is an active order on the maker exchange
is_active_maker_order
python
hummingbot/hummingbot
scripts/simple_xemm.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/simple_xemm.py
Apache-2.0
def exchanges_df(self) -> pd.DataFrame: """ Return a custom data frame of prices on maker vs taker exchanges for display purposes """ mid_price = self.connectors[self.config.maker_exchange].get_mid_price(self.config.maker_pair) maker_buy_result = self.connectors[self.config.maker...
Return a custom data frame of prices on maker vs taker exchanges for display purposes
exchanges_df
python
hummingbot/hummingbot
scripts/simple_xemm.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/simple_xemm.py
Apache-2.0
def active_orders_df(self) -> pd.DataFrame: """ Returns a custom data frame of all active maker orders for display purposes """ columns = ["Exchange", "Market", "Side", "Price", "Amount", "Spread Mid", "Spread Cancel", "Age"] data = [] mid_price = self.connectors[self.con...
Returns a custom data frame of all active maker orders for display purposes
active_orders_df
python
hummingbot/hummingbot
scripts/simple_xemm.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/simple_xemm.py
Apache-2.0
def get_funding_info_by_token(self, token): """ This method provides the funding rates across all the connectors """ funding_rates = {} for connector_name, connector in self.connectors.items(): trading_pair = self.get_trading_pair_for_connector(token, connector_name) ...
This method provides the funding rates across all the connectors
get_funding_info_by_token
python
hummingbot/hummingbot
scripts/v2_funding_rate_arb.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/v2_funding_rate_arb.py
Apache-2.0
def get_current_profitability_after_fees(self, token: str, connector_1: str, connector_2: str, side: TradeType): """ This methods compares the profitability of buying at market in the two exchanges. If the side is TradeType.BUY means that the operation is long on connector 1 and short on connect...
This methods compares the profitability of buying at market in the two exchanges. If the side is TradeType.BUY means that the operation is long on connector 1 and short on connector 2.
get_current_profitability_after_fees
python
hummingbot/hummingbot
scripts/v2_funding_rate_arb.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/v2_funding_rate_arb.py
Apache-2.0
def stop_actions_proposal(self) -> List[StopExecutorAction]: """ Once the funding rate arbitrage is created we are going to control the funding payments pnl and the current pnl of each of the executors at the cost of closing the open position at market. If that PNL is greater than the pr...
Once the funding rate arbitrage is created we are going to control the funding payments pnl and the current pnl of each of the executors at the cost of closing the open position at market. If that PNL is greater than the profitability_to_take_profit
stop_actions_proposal
python
hummingbot/hummingbot
scripts/v2_funding_rate_arb.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/v2_funding_rate_arb.py
Apache-2.0
def did_complete_funding_payment(self, funding_payment_completed_event: FundingPaymentCompletedEvent): """ Based on the funding payment event received, check if one of the active arbitrages matches to add the event to the list. """ token = funding_payment_completed_event.trading_...
Based on the funding payment event received, check if one of the active arbitrages matches to add the event to the list.
did_complete_funding_payment
python
hummingbot/hummingbot
scripts/v2_funding_rate_arb.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/v2_funding_rate_arb.py
Apache-2.0
def start(self, clock: Clock, timestamp: float) -> None: """ Start the strategy. :param clock: Clock to use. :param timestamp: Current time. """ self._last_timestamp = timestamp self.apply_initial_setting() if self.mqtt_enabled: self._pub = ETo...
Start the strategy. :param clock: Clock to use. :param timestamp: Current time.
start
python
hummingbot/hummingbot
scripts/v2_with_controllers.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/v2_with_controllers.py
Apache-2.0
def check_connector_status(self): """Check if the connector is ready""" if not self.connector_instance_xrpl.ready: self.logger().info("XRPL connector not ready yet, waiting...") self.connectors_ready = False return else: self.connectors_ready = Tru...
Check if the connector is ready
check_connector_status
python
hummingbot/hummingbot
scripts/xrpl_arb_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/xrpl_arb_example.py
Apache-2.0
def on_tick(self): """Main loop to check price and manage liquidity""" current_time = time.time() if current_time - self.last_refresh_time < self.config.refresh_interval_secs: return self.last_refresh_time = current_time if not self.connectors_ready: self...
Main loop to check price and manage liquidity
on_tick
python
hummingbot/hummingbot
scripts/xrpl_arb_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/xrpl_arb_example.py
Apache-2.0
async def on_stop(self): """Stop the strategy and close any open positions""" pass
Stop the strategy and close any open positions
on_stop
python
hummingbot/hummingbot
scripts/xrpl_arb_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/xrpl_arb_example.py
Apache-2.0
def calculate_amm_price_impact( self, initial_base_reserve: Decimal, initial_quote_reserve: Decimal, trade_amount: Decimal, is_selling_base: bool, ) -> Decimal: """ Calculates the price impact for a trade on a constant product AMM, where trade_amount a...
Calculates the price impact for a trade on a constant product AMM, where trade_amount always refers to an amount of the base asset. The price impact formula used is: Price Impact (%) = (Amount_Token_In / (Initial_Reserve_Token_In + Amount_Token_In)) * 100 Args: ini...
calculate_amm_price_impact
python
hummingbot/hummingbot
scripts/xrpl_arb_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/xrpl_arb_example.py
Apache-2.0
def get_amm_vwap_for_volume( self, initial_base_reserve: Decimal, initial_quote_reserve: Decimal, base_amount_to_trade: Decimal, is_buy_base: bool, ) -> Decimal: """ Calculates the Volume Weighted Average Price (VWAP) or effective price for trading a specific ...
Calculates the Volume Weighted Average Price (VWAP) or effective price for trading a specific amount of base asset on a constant product AMM. This price is in terms of quote_asset / base_asset. This calculation does not include any trading fees. Args: initial_base_...
get_amm_vwap_for_volume
python
hummingbot/hummingbot
scripts/xrpl_arb_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/xrpl_arb_example.py
Apache-2.0
async def check_price_and_open_position(self): """Check the current price and open a position if within range""" if self.position_opening or self.position_opened: return if self.connector_instance is None: self.logger().error("Connector instance is not available.") ...
Check the current price and open a position if within range
check_price_and_open_position
python
hummingbot/hummingbot
scripts/xrpl_liquidity_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/xrpl_liquidity_example.py
Apache-2.0
async def open_position(self): """Open a liquidity position around the target price""" if self.position_opening or self.position_opened: return if self.pool_info is None: self.logger().error("Cannot open position: Failed to get current pool info") self.positi...
Open a liquidity position around the target price
open_position
python
hummingbot/hummingbot
scripts/xrpl_liquidity_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/xrpl_liquidity_example.py
Apache-2.0
async def check_position_balance(self): """Check the balance of the position""" if not self.pool_info: self.logger().error("Cannot check position balance: Failed to get current pool info") return if self.wallet_address is None: self.logger().error("Cannot che...
Check the balance of the position
check_position_balance
python
hummingbot/hummingbot
scripts/xrpl_liquidity_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/xrpl_liquidity_example.py
Apache-2.0
def on_tick(self): """ Runs every tick_size seconds, this is the main operation of the strategy. This method does two things: - Refreshes the current bid and ask if they are set to None - Cancels the current bid or current ask if they are past their order_refresh_time T...
Runs every tick_size seconds, this is the main operation of the strategy. This method does two things: - Refreshes the current bid and ask if they are set to None - Cancels the current bid or current ask if they are past their order_refresh_time The canceled orders will be ref...
on_tick
python
hummingbot/hummingbot
scripts/community/adjusted_mid_price.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/adjusted_mid_price.py
Apache-2.0
def create_order(self, is_bid: bool) -> OrderCandidate: """ Create a propsal for the current bid or ask using the adjusted mid price. """ mid_price = Decimal(self.adjusted_mid_price()) bid_spread = Decimal(self.strategy["bid_spread"]) ask_spread = Decimal(self.strategy[...
Create a propsal for the current bid or ask using the adjusted mid price.
create_order
python
hummingbot/hummingbot
scripts/community/adjusted_mid_price.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/adjusted_mid_price.py
Apache-2.0
def adjusted_mid_price(self): """ Returns the price of a hypothetical buy and sell or the base asset where the amount is {strategy.test_volume} """ ask_result = self.connector.get_quote_volume_for_base_amount(self.strategy["pair"], True, self.strategy["test_volume"]) bid_result ...
Returns the price of a hypothetical buy and sell or the base asset where the amount is {strategy.test_volume}
adjusted_mid_price
python
hummingbot/hummingbot
scripts/community/adjusted_mid_price.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/adjusted_mid_price.py
Apache-2.0
def on_tick(self): """ Runs every tick_size seconds, this is the main operation of the strategy. - Create proposal (a list of order candidates) - Check the account balance and adjust the proposal accordingly (lower order amount if needed) - Lastly, execute the proposal on the exc...
Runs every tick_size seconds, this is the main operation of the strategy. - Create proposal (a list of order candidates) - Check the account balance and adjust the proposal accordingly (lower order amount if needed) - Lastly, execute the proposal on the exchange
on_tick
python
hummingbot/hummingbot
scripts/community/buy_dip_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/buy_dip_example.py
Apache-2.0
def create_proposal(self) -> List[OrderCandidate]: """ Creates and returns a proposal (a list of order candidate), in this strategy the list has 1 element at most. """ daily_closes = self._get_daily_close_list(self.trading_pair) start_index = (-1 * self.moving_avg_period) - 1 ...
Creates and returns a proposal (a list of order candidate), in this strategy the list has 1 element at most.
create_proposal
python
hummingbot/hummingbot
scripts/community/buy_dip_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/buy_dip_example.py
Apache-2.0
def execute_proposal(self, proposal: List[OrderCandidate]): """ Places the order candidates on the exchange, if it is not within cool off period and order candidate is valid. """ if self.last_ordered_ts > time.time() - self.cool_off_interval: return for order_candidat...
Places the order candidates on the exchange, if it is not within cool off period and order candidate is valid.
execute_proposal
python
hummingbot/hummingbot
scripts/community/buy_dip_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/buy_dip_example.py
Apache-2.0
def did_fill_order(self, event: OrderFilledEvent): """ Listens to fill order event to log it and notify the hummingbot application. """ msg = (f"({event.trading_pair}) {event.trade_type.name} order (price: {event.price}) of {event.amount} " f"{split_hb_trading_pair(event.t...
Listens to fill order event to log it and notify the hummingbot application.
did_fill_order
python
hummingbot/hummingbot
scripts/community/buy_dip_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/buy_dip_example.py
Apache-2.0
def _get_daily_close_list(self, trading_pair: str) -> List[Decimal]: """ Fetches binance candle stick data and returns a list daily close This is the API response data structure: [ [ 1499040000000, // Open time "0.01634790", // Open ...
Fetches binance candle stick data and returns a list daily close This is the API response data structure: [ [ 1499040000000, // Open time "0.01634790", // Open "0.80000000", // High "0.01575800", // Low ...
_get_daily_close_list
python
hummingbot/hummingbot
scripts/community/buy_dip_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/buy_dip_example.py
Apache-2.0
def get_signal(self): """ Generates the trading signal based on the composed signal value from multiple timeframes. Returns: int: The trading signal (-1 for sell, 0 for hold, 1 for buy). """ signals = [] for candle in self.candles: candles_df = sel...
Generates the trading signal based on the composed signal value from multiple timeframes. Returns: int: The trading signal (-1 for sell, 0 for hold, 1 for buy).
get_signal
python
hummingbot/hummingbot
scripts/community/directional_strategy_bb_rsi_multi_timeframe.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/directional_strategy_bb_rsi_multi_timeframe.py
Apache-2.0
def get_processed_df(candles): """ Retrieves the processed dataframe with Bollinger Bands and RSI values for a specific candlestick. Args: candles (pd.DataFrame): The raw candlestick dataframe. Returns: pd.DataFrame: The processed dataframe with Bollinger Bands an...
Retrieves the processed dataframe with Bollinger Bands and RSI values for a specific candlestick. Args: candles (pd.DataFrame): The raw candlestick dataframe. Returns: pd.DataFrame: The processed dataframe with Bollinger Bands and RSI values.
get_processed_df
python
hummingbot/hummingbot
scripts/community/directional_strategy_bb_rsi_multi_timeframe.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/directional_strategy_bb_rsi_multi_timeframe.py
Apache-2.0
def market_data_extra_info(self): """ Provides additional information about the market data for each candlestick. Returns: List[str]: A list of formatted strings containing market data information. """ lines = [] columns_to_show = ["timestamp", "open", "low", ...
Provides additional information about the market data for each candlestick. Returns: List[str]: A list of formatted strings containing market data information.
market_data_extra_info
python
hummingbot/hummingbot
scripts/community/directional_strategy_bb_rsi_multi_timeframe.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/directional_strategy_bb_rsi_multi_timeframe.py
Apache-2.0
def get_signal(self): """ Generates the trading signal based on the MACD and Bollinger Bands indicators. Returns: int: The trading signal (-1 for sell, 0 for hold, 1 for buy). """ candles_df = self.get_processed_df() last_candle = candles_df.iloc[-1] b...
Generates the trading signal based on the MACD and Bollinger Bands indicators. Returns: int: The trading signal (-1 for sell, 0 for hold, 1 for buy).
get_signal
python
hummingbot/hummingbot
scripts/community/directional_strategy_macd_bb.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/directional_strategy_macd_bb.py
Apache-2.0
def get_processed_df(self): """ Retrieves the processed dataframe with MACD and Bollinger Bands values. Returns: pd.DataFrame: The processed dataframe with MACD and Bollinger Bands values. """ candles_df = self.candles[0].candles_df candles_df.ta.bbands(length...
Retrieves the processed dataframe with MACD and Bollinger Bands values. Returns: pd.DataFrame: The processed dataframe with MACD and Bollinger Bands values.
get_processed_df
python
hummingbot/hummingbot
scripts/community/directional_strategy_macd_bb.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/directional_strategy_macd_bb.py
Apache-2.0
def market_data_extra_info(self): """ Provides additional information about the market data. Returns: List[str]: A list of formatted strings containing market data information. """ lines = [] columns_to_show = ["timestamp", "open", "low", "high", "close", "vol...
Provides additional information about the market data. Returns: List[str]: A list of formatted strings containing market data information.
market_data_extra_info
python
hummingbot/hummingbot
scripts/community/directional_strategy_macd_bb.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/directional_strategy_macd_bb.py
Apache-2.0
def get_signal(self): """ Generates the trading signal based on the RSI indicator. Returns: int: The trading signal (-1 for sell, 0 for hold, 1 for buy). """ candles_df = self.get_processed_df() rsi_value = candles_df.iat[-1, -1] if rsi_value > 70: ...
Generates the trading signal based on the RSI indicator. Returns: int: The trading signal (-1 for sell, 0 for hold, 1 for buy).
get_signal
python
hummingbot/hummingbot
scripts/community/directional_strategy_rsi_spot.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/directional_strategy_rsi_spot.py
Apache-2.0
def get_processed_df(self): """ Retrieves the processed dataframe with RSI values. Returns: pd.DataFrame: The processed dataframe with RSI values. """ candles_df = self.candles[0].candles_df candles_df.ta.rsi(length=7, append=True) return candles_df
Retrieves the processed dataframe with RSI values. Returns: pd.DataFrame: The processed dataframe with RSI values.
get_processed_df
python
hummingbot/hummingbot
scripts/community/directional_strategy_rsi_spot.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/directional_strategy_rsi_spot.py
Apache-2.0
def market_data_extra_info(self): """ Provides additional information about the market data to the format status. Returns: List[str]: A list of formatted strings containing market data information. """ lines = [] columns_to_show = ["timestamp", "open", "low", ...
Provides additional information about the market data to the format status. Returns: List[str]: A list of formatted strings containing market data information.
market_data_extra_info
python
hummingbot/hummingbot
scripts/community/directional_strategy_rsi_spot.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/directional_strategy_rsi_spot.py
Apache-2.0
def format_status(self) -> str: """ Displays the status of the fixed grid strategy Returns status of the current strategy on user balances and current active orders. """ if not self.ready_to_trade: return "Market connectors are not ready." lines = [] ...
Displays the status of the fixed grid strategy Returns status of the current strategy on user balances and current active orders.
format_status
python
hummingbot/hummingbot
scripts/community/fixed_grid.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/fixed_grid.py
Apache-2.0
def on_tick(self): """ Every order delay time the strategy will buy or sell the base asset. It will compute the cumulative order book volume until the spread and buy a percentage of that. The input of the strategy is in USD, but we will use the rate oracle to get a target base that wi...
Every order delay time the strategy will buy or sell the base asset. It will compute the cumulative order book volume until the spread and buy a percentage of that. The input of the strategy is in USD, but we will use the rate oracle to get a target base that will be static. - Use t...
on_tick
python
hummingbot/hummingbot
scripts/community/simple_vwap_no_config.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/simple_vwap_no_config.py
Apache-2.0
def on_tick(self): """ Every tick the strategy calculates the profitability of both direct and reverse direction. If the profitability of any direction is large enough it starts the arbitrage by creating and processing the first order candidate. """ if self.status == "NOT...
Every tick the strategy calculates the profitability of both direct and reverse direction. If the profitability of any direction is large enough it starts the arbitrage by creating and processing the first order candidate.
on_tick
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def init_strategy(self): """ Initializes strategy once before the start. """ self.status = "ACTIVE" self.check_trading_pair() self.set_trading_pair() self.set_order_side()
Initializes strategy once before the start.
init_strategy
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def check_trading_pair(self): """ Checks if the pairs specified in the config are suitable for the triangular arbitrage. They should have only 3 common assets with holding_asset among them. """ base_1, quote_1 = split_hb_trading_pair(self.first_pair) base_2, quote_2 = spl...
Checks if the pairs specified in the config are suitable for the triangular arbitrage. They should have only 3 common assets with holding_asset among them.
check_trading_pair
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def set_trading_pair(self): """ Rearrange trading pairs so that the first and last pair contains holding asset. We start trading round by selling holding asset and finish by buying it. Makes 2 tuples for "direct" and "reverse" directions and assigns them to the corresponding dictionary. ...
Rearrange trading pairs so that the first and last pair contains holding asset. We start trading round by selling holding asset and finish by buying it. Makes 2 tuples for "direct" and "reverse" directions and assigns them to the corresponding dictionary.
set_trading_pair
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def set_order_side(self): """ Sets order sides (1 = buy, 0 = sell) for already ordered trading pairs. Makes 2 tuples for "direct" and "reverse" directions and assigns them to the corresponding dictionary. """ base_1, quote_1 = split_hb_trading_pair(self.trading_pair["direct"][0])...
Sets order sides (1 = buy, 0 = sell) for already ordered trading pairs. Makes 2 tuples for "direct" and "reverse" directions and assigns them to the corresponding dictionary.
set_order_side
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def ready_for_new_orders(self) -> bool: """ Checks if we are ready for new orders: - Current status check - Holding asset balance check Return boolean True if we are ready and False otherwise """ if self.status == "NOT_ACTIVE": return False if...
Checks if we are ready for new orders: - Current status check - Holding asset balance check Return boolean True if we are ready and False otherwise
ready_for_new_orders
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def calculate_profit(self, trading_pair, order_side): """ Calculates profitability and order amounts for 3 trading pairs based on the orderbook depth. """ exchanged_amount = self.order_amount_in_holding_asset order_amount = [0, 0, 0] for i in range(3): order_...
Calculates profitability and order amounts for 3 trading pairs based on the orderbook depth.
calculate_profit
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def get_order_amount_from_exchanged_amount(self, pair, side, exchanged_amount) -> Decimal: """ Calculates order amount using the amount that we want to exchange. - If the side is buy then exchanged asset is a quote asset. Get base amount using the orderbook - If the side is sell then exc...
Calculates order amount using the amount that we want to exchange. - If the side is buy then exchanged asset is a quote asset. Get base amount using the orderbook - If the side is sell then exchanged asset is a base asset.
get_order_amount_from_exchanged_amount
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def get_base_amount_for_quote_volume(self, orderbook_entries, quote_volume) -> Decimal: """ Calculates base amount that you get for the quote volume using the orderbook entries """ cumulative_volume = 0. cumulative_base_amount = 0. quote_volume = float(quote_volume) ...
Calculates base amount that you get for the quote volume using the orderbook entries
get_base_amount_for_quote_volume
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def start_arbitrage(self, trading_pair, order_side, order_amount): """ Starts arbitrage by creating and processing the first order candidate """ first_candidate = self.create_order_candidate(trading_pair[0], order_side[0], order_amount[0]) if first_candidate: if self....
Starts arbitrage by creating and processing the first order candidate
start_arbitrage
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def create_order_candidate(self, pair, side, amount): """ Creates order candidate. Checks the quantized amount """ side = TradeType.BUY if side else TradeType.SELL price = self.connector.get_price_for_volume(pair, side, amount).result_price price_quantize = self.connector...
Creates order candidate. Checks the quantized amount
create_order_candidate
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def process_candidate(self, order_candidate, multiple_trials_enabled) -> bool: """ Checks order candidate balance and either places an order or sets a failure for the next trials """ order_candidate_adjusted = self.connector.budget_checker.adjust_candidate(order_candidate, all_or_none=Tr...
Checks order candidate balance and either places an order or sets a failure for the next trials
process_candidate
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def reset_order_candidate(self): """ Deletes order candidate variable and resets counter """ self.order_candidate = None self.place_order_trials_count = 0 self.place_order_failure = False
Deletes order candidate variable and resets counter
reset_order_candidate
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def process_next_pair(self, order_event): """ Processes 2nd or 3d order and finalizes the arbitrage - Gets the completed order index - Calculates order amount - Creates and processes order candidate - Finalizes arbitrage if the 3d order was completed """ e...
Processes 2nd or 3d order and finalizes the arbitrage - Gets the completed order index - Calculates order amount - Creates and processes order candidate - Finalizes arbitrage if the 3d order was completed
process_next_pair
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def finalize_arbitrage(self, final_exchanged_amount): """ Finalizes arbitrage - Calculates trading round profit - Updates total profit - Checks the kill switch threshold """ order_profit = round(final_exchanged_amount - self.initial_spent_amount, 6) order_...
Finalizes arbitrage - Calculates trading round profit - Updates total profit - Checks the kill switch threshold
finalize_arbitrage
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
def format_status(self) -> str: """ Returns status of the current strategy, total profit, current profitability of possible trades and balances. This function is called when status command is issued. """ if not self.ready_to_trade: return "Market connectors are not re...
Returns status of the current strategy, total profit, current profitability of possible trades and balances. This function is called when status command is issued.
format_status
python
hummingbot/hummingbot
scripts/community/triangular_arbitrage.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/community/triangular_arbitrage.py
Apache-2.0
async def on_stop(self): """ Without this functionality, the network iterator will continue running forever after stopping the strategy That's why is necessary to introduce this new feature to make a custom stop with the strategy. :return: """ self.eth_1m_candles.stop() ...
Without this functionality, the network iterator will continue running forever after stopping the strategy That's why is necessary to introduce this new feature to make a custom stop with the strategy. :return:
on_stop
python
hummingbot/hummingbot
scripts/utility/candles_example.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/utility/candles_example.py
Apache-2.0
def create_actions_proposal(self) -> List[CreateExecutorAction]: """ Create actions proposal based on the current state of the executors. """ create_actions = [] all_executors = self.get_all_executors() active_buy_position_executors = self.filter_executors( e...
Create actions proposal based on the current state of the executors.
create_actions_proposal
python
hummingbot/hummingbot
scripts/utility/v2_pmm_single_level.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/utility/v2_pmm_single_level.py
Apache-2.0
def executors_to_refresh(self) -> List[StopExecutorAction]: """ Create a list of actions to stop the executors that need to be refreshed. """ all_executors = self.get_all_executors() executors_to_refresh = self.filter_executors( executors=all_executors, fi...
Create a list of actions to stop the executors that need to be refreshed.
executors_to_refresh
python
hummingbot/hummingbot
scripts/utility/v2_pmm_single_level.py
https://github.com/hummingbot/hummingbot/blob/master/scripts/utility/v2_pmm_single_level.py
Apache-2.0
def async_to_sync(func: Callable[..., Coroutine[Any, Any, T]]) -> Callable[..., T]: """ Decorator to convert an async function into a function that can be called in sync context. If there's an existing running loop, it uses `run_until_complete()` to execute the coroutine. Otherwise, it uses `asyncio.ru...
Decorator to convert an async function into a function that can be called in sync context. If there's an existing running loop, it uses `run_until_complete()` to execute the coroutine. Otherwise, it uses `asyncio.run()`. :param func: The async function to be converted. :type func: Callable[..., A...
async_to_sync
python
hummingbot/hummingbot
test/isolated_asyncio_wrapper_test_case.py
https://github.com/hummingbot/hummingbot/blob/master/test/isolated_asyncio_wrapper_test_case.py
Apache-2.0
async def await_task_completion(tasks_name: Optional[str | List[str]]) -> None: """ Await the completion of the given task. Warning: This method relies on undocumented method of Task (get_coro()), as well as internals of Python coroutines (cr_code.co_name). :param str tasks_nam...
Await the completion of the given task. Warning: This method relies on undocumented method of Task (get_coro()), as well as internals of Python coroutines (cr_code.co_name). :param str tasks_name: The task name (or names) to be awaited. :return: The result of the task. ...
await_task_completion
python
hummingbot/hummingbot
test/isolated_asyncio_wrapper_test_case.py
https://github.com/hummingbot/hummingbot/blob/master/test/isolated_asyncio_wrapper_test_case.py
Apache-2.0
def _initialize(self: _LoggerProtocol): """ Initialize the test logger mixin by setting the default log level and initializing the log records list. """ self.level: _IntOrStr = 1 self.log_records: List[LogRecord] = []
Initialize the test logger mixin by setting the default log level and initializing the log records list.
_initialize
python
hummingbot/hummingbot
test/logger_mixin_for_test.py
https://github.com/hummingbot/hummingbot/blob/master/test/logger_mixin_for_test.py
Apache-2.0
def _to_loglevel(log_level: _IntOrStr) -> str: """ Convert a log level to a string. :params int | str log_level: The log level to convert. """ if isinstance(log_level, int): log_level = logging.getLevelName(log_level) return log_level
Convert a log level to a string. :params int | str log_level: The log level to convert.
_to_loglevel
python
hummingbot/hummingbot
test/logger_mixin_for_test.py
https://github.com/hummingbot/hummingbot/blob/master/test/logger_mixin_for_test.py
Apache-2.0
def set_loggers(self, loggers: List[HummingbotLogger] | HummingbotLogger): """ Set up the test logger mixin by adding the test logger to the provided loggers list. :params List[HummingbotLogger] | HummingbotLogger loggers: The loggers to add to the LoggerMixinForTest. """ # __ini...
Set up the test logger mixin by adding the test logger to the provided loggers list. :params List[HummingbotLogger] | HummingbotLogger loggers: The loggers to add to the LoggerMixinForTest.
set_loggers
python
hummingbot/hummingbot
test/logger_mixin_for_test.py
https://github.com/hummingbot/hummingbot/blob/master/test/logger_mixin_for_test.py
Apache-2.0
def is_logged(self, log_level: _IntOrStr, message: str) -> bool: """ Check if a certain message has been logged at a certain level. :params int | str log_level: The log level to check. :params str message: The message to check. """ log_level = self._to_loglevel(log_level)...
Check if a certain message has been logged at a certain level. :params int | str log_level: The log level to check. :params str message: The message to check.
is_logged
python
hummingbot/hummingbot
test/logger_mixin_for_test.py
https://github.com/hummingbot/hummingbot/blob/master/test/logger_mixin_for_test.py
Apache-2.0
def is_partially_logged(self, log_level: _IntOrStr, message: str) -> bool: """ Check if a certain message has been 'partially' logged at a certain level. This is useful for checking if a message has been logged with a dynamic value. :params int | str log_level: The log level to check. ...
Check if a certain message has been 'partially' logged at a certain level. This is useful for checking if a message has been logged with a dynamic value. :params int | str log_level: The log level to check. :params str message: The message to check.
is_partially_logged
python
hummingbot/hummingbot
test/logger_mixin_for_test.py
https://github.com/hummingbot/hummingbot/blob/master/test/logger_mixin_for_test.py
Apache-2.0
async def wait_for_logged(self, log_level: _IntOrStr, message: str, partial: bool = False, wait_s: float = 3) -> None: """ Wait for a certain message to be logged at a certain level. ...
Wait for a certain message to be logged at a certain level. :params int | str log_level: The log level to check. :params str message: The message to check. :params bool partial: Whether to check if the message is partially logged. :params float wait_s: The number of seconds to w...
wait_for_logged
python
hummingbot/hummingbot
test/logger_mixin_for_test.py
https://github.com/hummingbot/hummingbot/blob/master/test/logger_mixin_for_test.py
Apache-2.0
async def _dummy_coro(self, name, delay): """A dummy coroutine that simply sleeps for a delay.""" await asyncio.sleep(delay)
A dummy coroutine that simply sleeps for a delay.
_dummy_coro
python
hummingbot/hummingbot
test/test_isolated_asyncio_wrapper_test_case.py
https://github.com/hummingbot/hummingbot/blob/master/test/test_isolated_asyncio_wrapper_test_case.py
Apache-2.0
def test_account_positions(self): """ Test getting account positions by manually adding a position to the class member """ a_pos: Position = Position( "market1", PositionSide.LONG, Decimal("0"), Decimal("100"), Decimal("1"), Decimal("5") ) self.perpetual_tradi...
Test getting account positions by manually adding a position to the class member
test_account_positions
python
hummingbot/hummingbot
test/hummingbot/connector/test_perpetual_trading.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/test_perpetual_trading.py
Apache-2.0
def test_funding_info(self): """ Test getting funding infos by manually adding a funding info to the class member """ fInfo: FundingInfo = FundingInfo("pair1", Decimal(1), Decimal(2), 1000, Decimal(0.1)) self.perpetual_trading._funding_info["pair1"] = fInfo self.assertEqu...
Test getting funding infos by manually adding a funding info to the class member
test_funding_info
python
hummingbot/hummingbot
test/hummingbot/connector/test_perpetual_trading.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/test_perpetual_trading.py
Apache-2.0
def configure_successful_cancelation_response( self, order: InFlightOrder, mock_api: aioresponses, callback: Optional[Callable] = lambda *args, **kwargs: None, ) -> str: """ :return: the URL configured for the cancelation """ url = web_...
:return: the URL configured for the cancelation
configure_successful_cancelation_response
python
hummingbot/hummingbot
test/hummingbot/connector/derivative/bitget_perpetual/test_bitget_perpetual_derivative.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/derivative/bitget_perpetual/test_bitget_perpetual_derivative.py
Apache-2.0
def configure_one_successful_one_erroneous_cancel_all_response( self, successful_order: InFlightOrder, erroneous_order: InFlightOrder, mock_api: aioresponses, ) -> List[str]: """ :return: a list of all configured URLs for the cancelations """ ...
:return: a list of all configured URLs for the cancelations
configure_one_successful_one_erroneous_cancel_all_response
python
hummingbot/hummingbot
test/hummingbot/connector/derivative/bitget_perpetual/test_bitget_perpetual_derivative.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/derivative/bitget_perpetual/test_bitget_perpetual_derivative.py
Apache-2.0
def test_update_trading_fees_with_valid_and_invalid_pairs(self, mock_api): """ Test that trading fees are updated correctly for valid pairs, and invalid pairs are ignored in the trading pair map. """ self._simulate_trading_rules_initialized() self._simulate_trading_fees_i...
Test that trading fees are updated correctly for valid pairs, and invalid pairs are ignored in the trading pair map.
test_update_trading_fees_with_valid_and_invalid_pairs
python
hummingbot/hummingbot
test/hummingbot/connector/exchange/bybit/test_bybit_exchange.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/exchange/bybit/test_bybit_exchange.py
Apache-2.0
def test_update_time_synchronizer_with_exception(self): """Test that an exception other than CancelledError is logged.""" self.exchange._time_synchronizer.update_server_time_offset_with_time_provider = AsyncMock() self.exchange._time_synchronizer.update_server_time_offset_with_time_provider.side...
Test that an exception other than CancelledError is logged.
test_update_time_synchronizer_with_exception
python
hummingbot/hummingbot
test/hummingbot/connector/exchange/coinbase_advanced_trade/test_coinbase_advanced_trade_exchange.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/exchange/coinbase_advanced_trade/test_coinbase_advanced_trade_exchange.py
Apache-2.0
def test_update_time_synchronizer_with_cancelled_error(self): """Test that asyncio.CancelledError is raised.""" self.exchange._time_synchronizer.update_server_time_offset_with_time_provider = AsyncMock() self.exchange._time_synchronizer.update_server_time_offset_with_time_provider.side_effect = ...
Test that asyncio.CancelledError is raised.
test_update_time_synchronizer_with_cancelled_error
python
hummingbot/hummingbot
test/hummingbot/connector/exchange/coinbase_advanced_trade/test_coinbase_advanced_trade_exchange.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/exchange/coinbase_advanced_trade/test_coinbase_advanced_trade_exchange.py
Apache-2.0
def test_update_time_synchronizer_with_exception_pass_through(self): """Test that an exception other than CancelledError is not logged if pass_on_non_cancelled_error is True.""" self.exchange._time_synchronizer.update_server_time_offset_with_time_provider = AsyncMock() self.exchange._time_synchr...
Test that an exception other than CancelledError is not logged if pass_on_non_cancelled_error is True.
test_update_time_synchronizer_with_exception_pass_through
python
hummingbot/hummingbot
test/hummingbot/connector/exchange/coinbase_advanced_trade/test_coinbase_advanced_trade_exchange.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/exchange/coinbase_advanced_trade/test_coinbase_advanced_trade_exchange.py
Apache-2.0
def test_place_order_market_buy_successful(self, mock_time, mock_pair, mock_post): """Test successful market buy order placement.""" mock_post.return_value = {'success': True, 'success_response': {'order_id': '54321'}} mock_pair.return_value = 'BTC-USD' mock_time.return_value = 123456789...
Test successful market buy order placement.
test_place_order_market_buy_successful
python
hummingbot/hummingbot
test/hummingbot/connector/exchange/coinbase_advanced_trade/test_coinbase_advanced_trade_exchange.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/exchange/coinbase_advanced_trade/test_coinbase_advanced_trade_exchange.py
Apache-2.0
def test_place_order_market_sell_successful(self, mock_time, mock_pair, mock_post): """Test successful market sell order placement.""" mock_post.return_value = {'success': True, 'success_response': {'order_id': '98765'}} mock_pair.return_value = 'BTC-USD' mock_time.return_value = 1234567...
Test successful market sell order placement.
test_place_order_market_sell_successful
python
hummingbot/hummingbot
test/hummingbot/connector/exchange/coinbase_advanced_trade/test_coinbase_advanced_trade_exchange.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/exchange/coinbase_advanced_trade/test_coinbase_advanced_trade_exchange.py
Apache-2.0
async def test_order_status_determination( self, sleep_mock, fetch_account_transactions_mock, network_check_mock, get_account_mock ): """Test the order state determination logic in _request_order_status method""" # Setup common mocks to prevent await errors sleep_mock.return_value = ...
Test the order state determination logic in _request_order_status method
test_order_status_determination
python
hummingbot/hummingbot
test/hummingbot/connector/exchange/xrpl/test_xrpl_exchange.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/exchange/xrpl/test_xrpl_exchange.py
Apache-2.0
async def test_submit_transaction_success(self, mock_client_class): """Test successful transaction submission with proper mocking.""" # Setup client mock mock_client_instance = AsyncMock() mock_client_class.return_value.__aenter__.return_value = mock_client_instance # Setup tran...
Test successful transaction submission with proper mocking.
test_submit_transaction_success
python
hummingbot/hummingbot
test/hummingbot/connector/exchange/xrpl/test_xrpl_submit_transaction.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/exchange/xrpl/test_xrpl_submit_transaction.py
Apache-2.0
async def test_submit_transaction_error_response(self, mock_client_class): """Test transaction submission with error response.""" # Setup client mock mock_client_instance = AsyncMock() mock_client_class.return_value.__aenter__.return_value = mock_client_instance # Setup transact...
Test transaction submission with error response.
test_submit_transaction_error_response
python
hummingbot/hummingbot
test/hummingbot/connector/exchange/xrpl/test_xrpl_submit_transaction.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/connector/exchange/xrpl/test_xrpl_submit_transaction.py
Apache-2.0
def test_init(self): """ This lets us know if the initial values have changed and extends code coverage to the class's properties. """ nb = NetworkBase() self.assertEqual(nb.network_status, NetworkStatus.STOPPED) self.assertEqual(nb.check_network_task, None) ...
This lets us know if the initial values have changed and extends code coverage to the class's properties.
test_init
python
hummingbot/hummingbot
test/hummingbot/core/test_network_base.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/core/test_network_base.py
Apache-2.0
async def test_network(self): """ NetworkBase has a couple of method sketches that do not do anything but are used by child classes. """ nb = NetworkBase() await nb.start_network() await nb.stop_network() self.assertEqual(await nb.check_network(), Networ...
NetworkBase has a couple of method sketches that do not do anything but are used by child classes.
test_network
python
hummingbot/hummingbot
test/hummingbot/core/test_network_base.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/core/test_network_base.py
Apache-2.0
async def test_start_and_stop_network(self): """ Assert that start and stop update the started property. """ nb = NetworkBase() nb.start() self.assertEqual(nb.started, True) nb.stop() self.assertEqual(nb.started, False)
Assert that start and stop update the started property.
test_start_and_stop_network
python
hummingbot/hummingbot
test/hummingbot/core/test_network_base.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/core/test_network_base.py
Apache-2.0
async def test_update_network_status(self): """ Use SampleNetwork to test that the network status gets updated """ sample = SampleNetwork() self.assertEqual(sample.network_status, NetworkStatus.STOPPED) sample.check_network_interval = 0.1 sample.network_error_wa...
Use SampleNetwork to test that the network status gets updated
test_update_network_status
python
hummingbot/hummingbot
test/hummingbot/core/test_network_base.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/core/test_network_base.py
Apache-2.0
async def test_check_network_loop_raises_timeout(self, mock_sleep, mock_check_network): """ Test that the check_network_loop raises a timeout error """ mock_check_network.side_effect = [asyncio.TimeoutError] mock_sleep.side_effect = [asyncio.CancelledError] nb = SampleNet...
Test that the check_network_loop raises a timeout error
test_check_network_loop_raises_timeout
python
hummingbot/hummingbot
test/hummingbot/core/test_network_base.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/core/test_network_base.py
Apache-2.0
async def test_check_network_loop_raises_exception(self, mock_sleep, mock_check_network): """ Test that the check_network_loop raises an exception """ mock_check_network.side_effect = [Exception] mock_sleep.side_effect = [asyncio.CancelledError] nb = SampleNetwork() ...
Test that the check_network_loop raises an exception
test_check_network_loop_raises_exception
python
hummingbot/hummingbot
test/hummingbot/core/test_network_base.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/core/test_network_base.py
Apache-2.0
def test_property_setters(self): """Test property setters for api_key and api_tier properties""" rate_source = CoinGeckoRateSource(extra_token_ids=[]) # Verify initial state self.assertEqual("", rate_source.api_key) self.assertEqual(CoinGeckoAPITier.PUBLIC, rate_source.api_tier)...
Test property setters for api_key and api_tier properties
test_property_setters
python
hummingbot/hummingbot
test/hummingbot/core/rate_oracle/sources/test_coin_gecko_rate_source.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/core/rate_oracle/sources/test_coin_gecko_rate_source.py
Apache-2.0
async def foo_three_times(self, target): """ This function runs three times. It raises FooException when the target is not met. When FooException is called, async_retry increments a counter and logs the error, if the counter is three and foo_three_times still fails, then it will raise ...
This function runs three times. It raises FooException when the target is not met. When FooException is called, async_retry increments a counter and logs the error, if the counter is three and foo_three_times still fails, then it will raise AllTriesFailedException.
foo_three_times
python
hummingbot/hummingbot
test/hummingbot/core/utils/test_async_retry.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/core/utils/test_async_retry.py
Apache-2.0
async def bar_three_times(self, target): """ This function runs three times. It raises BarException when the target is not met. When FooException is called, async_retry increments a counter, if the counter is three and foo_three_times still fails, then it will raise AllTriesFailedExcepti...
This function runs three times. It raises BarException when the target is not met. When FooException is called, async_retry increments a counter, if the counter is three and foo_three_times still fails, then it will raise AllTriesFailedException.
bar_three_times
python
hummingbot/hummingbot
test/hummingbot/core/utils/test_async_retry.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/core/utils/test_async_retry.py
Apache-2.0
def _verify_api_auth_headers(self, mock_api: aioresponses, url: str, expected_header: Optional[str] = None, expected_key: Optional[str] = None): """Helper to verify auth headers in requests""" found_request = False for req_key, req_data in mock_api.requests.items...
Helper to verify auth headers in requests
_verify_api_auth_headers
python
hummingbot/hummingbot
test/hummingbot/data_feed/test_coin_gecko_data_feed.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/data_feed/test_coin_gecko_data_feed.py
Apache-2.0
def test_execute_request_with_demo_api_key(self, mock_api: aioresponses): """Test that _execute_request adds DEMO authentication headers when API key is provided""" demo_key = "demo_api_key" demo_data_feed = CoinGeckoDataFeed(api_key=demo_key, api_tier=CONSTANTS.CoinGeckoAPITier.DEMO) ur...
Test that _execute_request adds DEMO authentication headers when API key is provided
test_execute_request_with_demo_api_key
python
hummingbot/hummingbot
test/hummingbot/data_feed/test_coin_gecko_data_feed.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/data_feed/test_coin_gecko_data_feed.py
Apache-2.0
def test_execute_request_with_pro_api_key(self, mock_api: aioresponses): """Test that _execute_request adds PRO authentication headers when API key is provided""" pro_key = "pro_api_key" pro_data_feed = CoinGeckoDataFeed(api_key=pro_key, api_tier=CONSTANTS.CoinGeckoAPITier.PRO) url = f"{...
Test that _execute_request adds PRO authentication headers when API key is provided
test_execute_request_with_pro_api_key
python
hummingbot/hummingbot
test/hummingbot/data_feed/test_coin_gecko_data_feed.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/data_feed/test_coin_gecko_data_feed.py
Apache-2.0
def test_execute_request_with_no_api_key(self, mock_api: aioresponses): """Test that _execute_request does not add authentication headers when no API key is provided""" public_data_feed = CoinGeckoDataFeed() url = f"{PUBLIC.base_url}{CONSTANTS.SUPPORTED_VS_TOKENS_REST_ENDPOINT}" data = [...
Test that _execute_request does not add authentication headers when no API key is provided
test_execute_request_with_no_api_key
python
hummingbot/hummingbot
test/hummingbot/data_feed/test_coin_gecko_data_feed.py
https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/data_feed/test_coin_gecko_data_feed.py
Apache-2.0