nectar.market module
- class nectar.market.Market(base: str | Asset | None = None, quote: str | Asset | None = None, blockchain_instance: Any | None = None, **kwargs: Any)
Bases:
dictThis class allows access to the internal market for trading, etc. (Hive-only).
- Parameters:
- Returns:
Blockchain Market
- Return type:
dictionary with overloaded methods
Instances of this class are dictionaries that come with additional methods (see below) that allow dealing with a market and its corresponding functions.
This class tries to identify two assets as provided in the parameters in one of the following forms:
baseandquoteare valid assets (according tonectar.asset.Asset)base:quoteseparated with:base/quoteseparated with/base-quoteseparated with-
Note
Throughout this library, the
quotesymbol will be presented first (e.g.HIVE:HBDwithHIVEbeing the quote), while thebaseonly refers to a secondary asset for a trade. This means, if you callnectar.market.Market.sell()ornectar.market.Market.buy(), you will sell/buy only quote and obtain/pay only base.- accountopenorders(account: str | Account | None = None, raw_data: bool = False) List[Order] | List[Dict[str, Any]] | None
Returns open Orders
- Parameters:
account (Account) – Account name or instance of Account to show orders for in this market
raw_data (bool) – (optional) returns raw data if set True, or a list of Order() instances if False (defaults to False)
- static btc_usd_ticker(verbose: bool = False) float
Return the market-weighted BTC/USD price aggregated from multiple external sources.
Queries a set of public endpoints (currently CoinGecko; legacy support for Bitfinex, GDAX, Kraken, OKCoin, Bitstamp is present) and computes a volume-weighted average price (VWAP) across successful responses.
- Parameters:
verbose (bool): If True, prints the raw price/volume map collected from each source.
- Returns:
float: The VWAP of BTC in USD computed from available sources.
- Raises:
RuntimeError: If no valid price data could be obtained from any source after several attempts.
- buy(price: str | Price | float, amount: str | Amount, expiration: int | None = None, killfill: bool = False, account: str | Account | None = None, orderid: int | None = None, returnOrderId: bool = False) Dict[str, Any] | str
Place a buy order (limit order) on this market.
Prices are expressed in the market’s base/quote orientation (HIVE per HBD in HBD_HIVE). This method submits a limit-order-create operation that effectively places a sell order of the base asset to acquire the requested amount of the quote asset.
- Parameters:
price (float or Price): Price expressed in base per quote (e.g., HIVE per HBD). amount (number or str or Amount): Amount of the quote asset to buy. expiration (int, optional): Order lifetime in seconds (default: configured order-expiration, typically 7 days). killfill (bool, optional): If True, set fill_or_kill on the order (defaults to False). account (str, optional): Account name that will own and broadcast the order. If omitted, default_account from config is used; a ValueError is raised if none is available. orderid (int, optional): Explicit client-side order id. If omitted one is randomly generated. returnOrderId (bool or str, optional): If truthy (or set to “head”/”irreversible”), the call will wait for the transaction and attach the assigned order id to the returned transaction under the “orderid” key.
- Returns:
dict: The finalized broadcast transaction object returned by the blockchain client. If returnOrderId was used, the dict includes an “orderid” field.
- Raises:
ValueError: If no account can be resolved. AssertionError: If an Amount is provided whose asset symbol does not match the market quote.
- Notes:
Because buy orders are implemented as limit-sell orders of the base asset, the trade can result in receiving more of the quote asset than requested if matching orders exist at better prices.
- cancel(orderNumbers: int | List[int] | Set[int] | Tuple[int, ...], account: str | Account | None = None, **kwargs: Any) Dict[str, Any]
Cancels an order you have placed in a given market. Requires only the “orderNumbers”.
- Parameters:
orderNumbers (int, list) – A single order number or a list of order numbers
- get_string(separator: str = ':') str
Return the market identifier as “QUOTE{separator}BASE” (e.g. “HIVE:HBD”).
- Parameters:
separator (str): Token placed between quote and base symbols. Defaults to “:”.
- Returns:
str: Formatted market string in the form “<quote><separator><base>”.
- static hive_btc_ticker() float
Return the HIVE/BTC price as a volume-weighted average from multiple public exchanges.
Queries several public APIs (CoinGecko and others) to collect recent HIVE/BTC prices and 24h volumes, then computes a volume-weighted average price (VWAP). The function retries up to 5 times if no valid responses are obtained.
- Returns:
float: VWAP price expressed in BTC per 1 HIVE.
- Raises:
RuntimeError: If no valid price data could be obtained from any source.
- hive_usd_implied() float
Returns the current HIVE/USD market price
- market_history(bucket_seconds: int | float = 300, start_age: int = 3600, end_age: int = 0, raw_data: bool = False) List[Dict[str, Any]] | Any
Return market history buckets for a time window.
This fetches aggregated market history buckets (filled orders) for the market over a window defined by start_age and end_age and grouped by bucket_seconds. bucket_seconds may be provided either as a numeric bucket size (seconds) or as an index into available buckets returned by market_history_buckets(). When raw_data is False any bucket “open” timestamp strings are normalized to a consistent formatted datetime string.
- Parameters:
bucket_seconds (int): Bucket size in seconds or an index into market_history_buckets(). start_age (int): Age in seconds from now to the start of the window (default 3600 seconds). end_age (int): Age in seconds from now to the end of the window (default 0 = now). raw_data (bool): If True, return the raw RPC response without normalizing timestamps.
- Returns:
list: A list of bucket dicts (or the raw RPC list when raw_data is True). Each bucket contains fields such as ‘open’, ‘seconds’, ‘open_hbd’, ‘close_hbd’, ‘high_hbd’, ‘low_hbd’, ‘hbd_volume’, ‘open_hive’, ‘close_hive’, ‘high_hive’, ‘low_hive’, ‘hive_volume’, and ‘id’ when available.
- Raises:
ValueError: If bucket_seconds is not a valid bucket size or valid index into available buckets.
- market_history_buckets() List[int]
- orderbook(limit: int = 25, raw_data: bool = False) Dict[str, Any] | Any
Returns the order book for the HBD/HIVE market.
- Parameters:
limit (int) – Limit the amount of orders (default: 25)
Sample output (raw_data=False):
{ 'asks': [ 380.510 HIVE 460.291 HBD @ 1.209669 HBD/HIVE, 53.785 HIVE 65.063 HBD @ 1.209687 HBD/HIVE ], 'bids': [ 0.292 HIVE 0.353 HBD @ 1.208904 HBD/HIVE, 8.498 HIVE 10.262 HBD @ 1.207578 HBD/HIVE ], 'asks_date': [ datetime.datetime(2018, 4, 30, 21, 7, 24, tzinfo=<UTC>), datetime.datetime(2018, 4, 30, 18, 12, 18, tzinfo=<UTC>) ], 'bids_date': [ datetime.datetime(2018, 4, 30, 21, 1, 21, tzinfo=<UTC>), datetime.datetime(2018, 4, 30, 20, 38, 21, tzinfo=<UTC>) ] }Sample output (raw_data=True):
{ 'asks': [ { 'order_price': {'base': '8.000 HIVE', 'quote': '9.618 HBD'}, 'real_price': '1.20225000000000004', 'hive': 4565, 'hbd': 5488, 'created': '2018-04-30T21:12:45' } ], 'bids': [ { 'order_price': {'base': '10.000 HBD', 'quote': '8.333 HIVE'}, 'real_price': '1.20004800192007677', 'hive': 8333, 'hbd': 10000, 'created': '2018-04-30T20:29:33' } ] }
Note
Each bid is an instance of class:nectar.price.Order and thus carries the keys
base,quoteandprice. From those you can obtain the actual amounts for sale
- recent_trades(limit: int = 25, raw_data: bool = False) List[FilledOrder] | List[Dict[str, Any]]
Return recent trades for this market.
By default returns up to limit most recent trades wrapped as FilledOrder objects; if raw_data is True the raw trade dictionaries from the market_history API are returned instead.
- Parameters:
limit (int): Maximum number of trades to retrieve (default: 25). raw_data (bool): If True, return raw API trade entries; if False, return a list of FilledOrder instances constructed with this market’s blockchain instance.
- Returns:
list: A list of FilledOrder objects when raw_data is False, or a list of raw trade dicts as returned by the market_history API when raw_data is True.
- sell(price: str | Price | float, amount: str | Amount, expiration: int | None = None, killfill: bool = False, account: str | Account | None = None, orderid: int | None = None, returnOrderId: bool = False) Dict[str, Any] | str
Place a limit sell order on this market, selling the market’s quote asset for its base asset.
This creates a Limit_order_create operation where amount_to_sell is the provided amount in the market’s quote asset and min_to_receive is amount * price in the market’s base asset.
- Parameters:
price (float or Price): Price expressed as base per quote (e.g., in HBD_HIVE market, a price of 3 means 1 HBD = 3 HIVE). amount (number or str or Amount): Quantity of the quote asset to sell; may be an Amount instance, a string (e.g., “10.000 HBD”), or a numeric value. expiration (int, optional): Order lifetime in seconds; defaults to the node/configured order-expiration (typically 7 days). killfill (bool, optional): If True, treat the order as fill-or-kill (cancel if not fully filled). Defaults to False. account (str, optional): Account name placing the order. If omitted, the configured default_account is used. Raises ValueError if no account is available. orderid (int, optional): Client-provided order identifier; a random 32-bit id is used if not supplied. returnOrderId (bool or str, optional): If truthy (or set to “head”/”irreversible”), the call will wait according to the blocking mode and the returned transaction will include an “orderid” field.
- Returns:
dict: The finalized transaction object returned by the blockchain finalizeOp call. If returnOrderId is used, the dict will include an “orderid” key.
- Raises:
ValueError: If no account is provided or available from configuration. AssertionError: If an Amount is provided whose asset symbol does not match the market’s quote asset.
- ticker(raw_data: bool = False) Dict[str, Any] | Any
Return the market ticker for this Market (HIVE:HBD).
By default returns a dict with Price objects for ‘highest_bid’, ‘latest’, and ‘lowest_ask’, a float ‘percent_change’ (24h), and Amount objects for ‘hbd_volume’ and ‘hive_volume’ when present. If raw_data is True, returns the unprocessed RPC result.
- Parameters:
raw_data (bool): If True, return the raw market_history RPC response instead of mapped objects.
- Returns:
dict or Any: Mapped ticker dictionary (prices as Price, volumes as Amount) or raw RPC data.
- Notes:
Prices are expressed as HBD per HIVE.
- trade_history(start: datetime | date | time | None = None, stop: datetime | date | time | None = None, limit: int = 25, raw_data: bool = False) List[FilledOrder] | List[Dict[str, Any]]
Returns the trade history for the internal market
- Parameters:
start (datetime) – Start date
stop (datetime) – Stop date
limit (int) – Defines how many trades are fetched at each interval point
raw_data (bool) – when True, the raw data are returned
- trades(limit: int = 100, start: datetime | date | time | None = None, stop: datetime | date | time | None = None, raw_data: bool = False) List[FilledOrder] | List[Dict[str, Any]]
Returns your trade history for a given market.
- Parameters:
limit (int) – Limit the amount of orders (default: 100)
start (datetime) – start time
stop (datetime) – stop time
- volume24h(raw_data: bool = False) Dict[str, Amount] | Any | None
Return 24-hour trading volume for this market.
If raw_data is True, returns the raw result from the blockchain market_history RPC. Otherwise, if the RPC result contains ‘hbd_volume’ and ‘hive_volume’, returns a dict mapping asset symbols to Amount objects, e.g. { “HBD”: Amount(…), “HIVE”: Amount(…) }. If the expected volume keys are not present, returns None.
- Parameters:
raw_data (bool): If True, return the unprocessed RPC response.