INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
handle portfolio updates
def handlePortfolio(self, msg): """ handle portfolio updates """ # log handler msg self.log_msg("portfolio", msg) # contract identifier contract_tuple = self.contract_to_tuple(msg.contract) contractString = self.contractString(contract_tuple) # try creating the...
handle order open & status
def handleOrders(self, msg): """ handle order open & status """ """ It is possible that orderStatus() may return duplicate messages. It is essential that you filter the message accordingly. """ # log handler msg self.log_msg("order", msg) # get server ti...
https://www.interactivebrokers.com/en/software/api/apiguide/java/updatemktdepth.htm https://www.interactivebrokers.com/en/software/api/apiguide/java/updatemktdepthl2.htm
def handleMarketDepth(self, msg): """ https://www.interactivebrokers.com/en/software/api/apiguide/java/updatemktdepth.htm https://www.interactivebrokers.com/en/software/api/apiguide/java/updatemktdepthl2.htm """ # make sure symbol exists if msg.tickerId not in self.marke...
holds latest tick bid/ask/last price
def handleTickGeneric(self, msg): """ holds latest tick bid/ask/last price """ df2use = self.marketData if self.contracts[msg.tickerId].m_secType in ("OPT", "FOP"): df2use = self.optionsData # create tick holder for ticker if msg.tickerId not in df2u...
holds latest tick bid/ask/last price
def handleTickPrice(self, msg): """ holds latest tick bid/ask/last price """ # self.log.debug("[TICK PRICE]: %s - %s", dataTypes["PRICE_TICKS"][msg.field], msg) # return if msg.price < 0: return df2use = self.marketData canAutoExecute = msg.c...
holds latest tick bid/ask/last size
def handleTickSize(self, msg): """ holds latest tick bid/ask/last size """ if msg.size < 0: return df2use = self.marketData if self.contracts[msg.tickerId].m_secType in ("OPT", "FOP"): df2use = self.optionsData # create tick holder for t...
holds latest tick bid/ask/last timestamp
def handleTickString(self, msg): """ holds latest tick bid/ask/last timestamp """ df2use = self.marketData if self.contracts[msg.tickerId].m_secType in ("OPT", "FOP"): df2use = self.optionsData # create tick holder for ticker if msg.tickerId not in d...
holds latest option data timestamp only option price is kept at the moment https://www.interactivebrokers.com/en/software/api/apiguide/java/tickoptioncomputation.htm
def handleTickOptionComputation(self, msg): """ holds latest option data timestamp only option price is kept at the moment https://www.interactivebrokers.com/en/software/api/apiguide/java/tickoptioncomputation.htm """ def calc_generic_val(data, field): last_va...
adds order to triggerable list
def createTriggerableTrailingStop(self, symbol, quantity=1, triggerPrice=0, trailPercent=100., trailAmount=0., parentId=0, stopOrderId=None, **kwargs): """ adds order to triggerable list """ ticksize = self.contractDetails(symbol)["m_minTick"] self.triggerableTrailingSt...
adds trailing stop to monitor list
def registerTrailingStop(self, tickerId, orderId=0, quantity=1, lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs): """ adds trailing stop to monitor list """ ticksize = self.contractDetails(tickerId)["m_minTick"] trailingStop = self.trailingStops[tickerId] = { ...
modify stop order
def modifyStopOrder(self, orderId, parentId, newStop, quantity, transmit=True, account=None): """ modify stop order """ if orderId in self.orders.keys(): order = self.createStopOrder( quantity = quantity, parentId = parentId, ...
software-based trailing stop
def handleTrailingStops(self, tickerId): """ software-based trailing stop """ # existing? if tickerId not in self.trailingStops.keys(): return None # continue trailingStop = self.trailingStops[tickerId] price = self.marketData[tickerId]['last'][0]...
trigger waiting trailing stops
def triggerTrailingStops(self, tickerId): """ trigger waiting trailing stops """ # print('.') # test symbol = self.tickerSymbol(tickerId) price = self.marketData[tickerId]['last'][0] # contract = self.contracts[tickerId] if symbol in self.triggerableTrailingStop...
returns the tickerId for the symbol or sets one if it doesn't exits
def tickerId(self, contract_identifier): """ returns the tickerId for the symbol or sets one if it doesn't exits """ # contract passed instead of symbol? symbol = contract_identifier if isinstance(symbol, Contract): symbol = self.contractString(symbol)...
returns string from contract tuple
def contractString(self, contract, seperator="_"): """ returns string from contract tuple """ localSymbol = "" contractTuple = contract if type(contract) != tuple: localSymbol = contract.m_localSymbol contractTuple = self.contract_to_tuple(contract) # b...
returns string from contract tuple
def contractDetails(self, contract_identifier): """ returns string from contract tuple """ if isinstance(contract_identifier, Contract): tickerId = self.tickerId(contract_identifier) else: if str(contract_identifier).isdigit(): tickerId = contract_identif...
tells if is this contract has sub-contract with expiries/strikes/sides
def isMultiContract(self, contract): """ tells if is this contract has sub-contract with expiries/strikes/sides """ if contract.m_secType == "FUT" and contract.m_expiry == "": return True if contract.m_secType in ["OPT", "FOP"] and \ (contract.m_expiry == "" or contr...
Used for FX, etc: createCashContract("EUR", currency="USD")
def createCashContract(self, symbol, currency="USD", exchange="IDEALPRO"): """ Used for FX, etc: createCashContract("EUR", currency="USD") """ contract_tuple = (symbol, "CASH", exchange, currency, "", 0.0, "") contract = self.createContract(contract_tuple) return contract
Used for indexes (SPX, DJX, ...)
def createIndexContract(self, symbol, currency="USD", exchange="CBOE"): """ Used for indexes (SPX, DJX, ...) """ contract_tuple = (symbol, "IND", exchange, currency, "", 0.0, "") contract = self.createContract(contract_tuple) return contract
Creates TARGET order
def createTargetOrder(self, quantity, parentId=0, target=0., orderType=None, transmit=True, group=None, tif="DAY", rth=False, account=None): """ Creates TARGET order """ order = self.createOrder(quantity, price = target, transmit = tra...
Creates STOP order
def createStopOrder(self, quantity, parentId=0, stop=0., trail=None, transmit=True, group=None, stop_limit=False, rth=False, tif="DAY", account=None): """ Creates STOP order """ if trail: if trail == "percent": order = self.createOrder(quantity, ...
convert hard stop order to trailing stop order
def createTrailingStopOrder(self, contract, quantity, parentId=0, trailPercent=100., group=None, triggerPrice=None, account=None): """ convert hard stop order to trailing stop order """ if parentId not in self.orders: raise ValueError("Order #" + str(parentId) + " do...
creates One Cancels All Bracket Order trailingStop = None (regular stop) / percent / amount
def createBracketOrder(self, contract, quantity, entry=0., target=0., stop=0., targetType=None, trailingStop=None, group=None, tif="DAY", fillorkill=False, iceberg=False, rth=False, stop_limit=False, transmit=True, account=None, **kwargs): """ creates One...
Place order on IB TWS
def placeOrder(self, contract, order, orderId=None, account=None): """ Place order on IB TWS """ # get latest order id before submitting an order self.requestOrderIds() # continue... useOrderId = self.orderId if orderId == None else orderId if account: order...
cancel order on IB TWS
def cancelOrder(self, orderId): """ cancel order on IB TWS """ self.ibConn.cancelOrder(orderId) # update order id for next time self.requestOrderIds() return orderId
Request open orders - loads up orders that wasn't created using this session
def requestOpenOrders(self, all_clients=False): """ Request open orders - loads up orders that wasn't created using this session """ if all_clients: self.ibConn.reqAllOpenOrders() self.ibConn.reqOpenOrders()
Register to streaming market data updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqmktdepth.htm
def requestMarketDepth(self, contracts=None, num_rows=10): """ Register to streaming market data updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqmktdepth.htm """ if num_rows > 10: num_rows = 10 if contracts == None: co...
Cancel streaming market data for contract https://www.interactivebrokers.com/en/software/api/apiguide/java/cancelmktdepth.htm
def cancelMarketDepth(self, contracts=None): """ Cancel streaming market data for contract https://www.interactivebrokers.com/en/software/api/apiguide/java/cancelmktdepth.htm """ if contracts == None: contracts = list(self.contracts.values()) elif not isinstan...
Register to streaming market data updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqmktdata.htm
def requestMarketData(self, contracts=None, snapshot=False): """ Register to streaming market data updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqmktdata.htm """ if contracts == None: contracts = list(self.contracts.values()) elif ...
Cancel streaming market data for contract https://www.interactivebrokers.com/en/software/api/apiguide/java/cancelmktdata.htm
def cancelMarketData(self, contracts=None): """ Cancel streaming market data for contract https://www.interactivebrokers.com/en/software/api/apiguide/java/cancelmktdata.htm """ if contracts == None: contracts = list(self.contracts.values()) elif not isinstance...
Download to historical data https://www.interactivebrokers.com/en/software/api/apiguide/java/reqhistoricaldata.htm
def requestHistoricalData(self, contracts=None, resolution="1 min", lookback="1 D", data="TRADES", end_datetime=None, rth=False, csv_path=None, format_date=2, utc=False): """ Download to historical data https://www.interactivebrokers.com/en/software/api/apiguide/java/req...
cancel historical data stream
def cancelHistoricalData(self, contracts=None): """ cancel historical data stream """ if contracts == None: contracts = list(self.contracts.values()) elif not isinstance(contracts, list): contracts = [contracts] for contract in contracts: # tickerId =...
Request/cancel request real-time position data for all accounts.
def requestPositionUpdates(self, subscribe=True): """ Request/cancel request real-time position data for all accounts. """ if self.subscribePositions != subscribe: self.subscribePositions = subscribe if subscribe == True: self.ibConn.reqPositions() els...
Register to account updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqaccountupdates.htm
def requestAccountUpdates(self, subscribe=True): """ Register to account updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqaccountupdates.htm """ if self.subscribeAccount != subscribe: self.subscribeAccount = subscribe self.ibConn...
Register to contract details https://www.interactivebrokers.com/en/software/api/apiguide/java/reqcontractdetails.htm
def requestContractDetails(self, contract): """ Register to contract details https://www.interactivebrokers.com/en/software/api/apiguide/java/reqcontractdetails.htm """ self.ibConn.reqContractDetails(self.tickerId(contract), contract)
Get contracts conId
def getConId(self, contract_identifier): """ Get contracts conId """ details = self.contractDetails(contract_identifier) if len(details["contracts"]) > 1: return details["m_underConId"] return details["m_summary"]["m_conId"]
create combo leg https://www.interactivebrokers.com/en/software/api/apiguide/java/comboleg.htm
def createComboLeg(self, contract, action, ratio=1, exchange=None): """ create combo leg https://www.interactivebrokers.com/en/software/api/apiguide/java/comboleg.htm """ leg = ComboLeg() loops = 0 conId = 0 while conId == 0 and loops < 100: conId = s...
Used for ComboLegs. Expecting list of legs
def createComboContract(self, symbol, legs, currency="USD", exchange=None): """ Used for ComboLegs. Expecting list of legs """ exchange = legs[0].m_exchange if exchange is None else exchange contract_tuple = (symbol, "BAG", exchange, currency, "", 0.0, "") contract = self.createContract(...
return strikes of contract / "multi" contract's contracts
def getStrikes(self, contract_identifier, smin=None, smax=None): """ return strikes of contract / "multi" contract's contracts """ strikes = [] contracts = self.contractDetails(contract_identifier)["contracts"] if contracts[0].m_secType not in ("FOP", "OPT"): return [] ...
return expiration of contract / "multi" contract's contracts
def getExpirations(self, contract_identifier, expired=0): """ return expiration of contract / "multi" contract's contracts """ expirations = [] contracts = self.contractDetails(contract_identifier)["contracts"] if contracts[0].m_secType not in ("FUT", "FOP", "OPT"): return [...
:Return: a logger with the given `name` and optional `level`.
def createLogger(name, level=logging.WARNING): """:Return: a logger with the given `name` and optional `level`.""" logger = logging.getLogger(name) logger.setLevel(level) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')) ...
Convert an IBPy Order object to a dict containing any non-default values.
def order_to_dict(order): """Convert an IBPy Order object to a dict containing any non-default values.""" default = Order() return {field: val for field, val in vars(order).items() if val != getattr(default, field, None)}
converts naive (usually local) timezone to UTC)
def local_to_utc(df): """ converts naive (usually local) timezone to UTC) """ try: offset_hour = -(datetime.now() - datetime.utcnow()).seconds except: offset_hour = time.altzone if time.daylight else time.timezone offset_hour = offset_hour // 3600 offset_hour = offset_hour if offset...
Convert an IBPy Contract object to a dict containing any non-default values.
def contract_to_dict(contract): """Convert an IBPy Contract object to a dict containing any non-default values.""" default = Contract() return {field: val for field, val in vars(contract).items() if val != getattr(default, field, None)}
Get UTM code given a zone and direction Direction is encoded as NORTH=6, SOUTH=7, while zone is the UTM zone number zero-padded. For instance, the code 32604 is returned for zone number 4, north direction. :param zone: UTM zone number :type zone: int :param direction: Direction enum type :type...
def _get_utm_code(zone, direction): """ Get UTM code given a zone and direction Direction is encoded as NORTH=6, SOUTH=7, while zone is the UTM zone number zero-padded. For instance, the code 32604 is returned for zone number 4, north direction. :param zone: UTM zone number :type zone: int :pa...
Get name and code for UTM coordinates :param zone: UTM zone number :type zone: int :param direction: Direction enum type :type direction: Enum, optional (default=NORTH) :return: Name and code of UTM coordinates :rtype: str, str
def _get_utm_name_value_pair(zone, direction=_Direction.NORTH): """ Get name and code for UTM coordinates :param zone: UTM zone number :type zone: int :param direction: Direction enum type :type direction: Enum, optional (default=NORTH) :return: Name and code of UTM coordinates :rtype: str,...
Parses user input for class CRS :param cls: class object :param value: user input for CRS :type value: str, int or CRS
def _crs_parser(cls, value): """ Parses user input for class CRS :param cls: class object :param value: user input for CRS :type value: str, int or CRS """ parsed_value = value if isinstance(parsed_value, int): parsed_value = str(parsed_value) if isinstance(parsed_value, str): ...
Maps data source to string identifier for WFS :param data_source: One of the supported data sources :type: DataSource :return: Product identifier for WFS :rtype: str
def get_wfs_typename(cls, data_source): """ Maps data source to string identifier for WFS :param data_source: One of the supported data sources :type: DataSource :return: Product identifier for WFS :rtype: str """ is_eocloud = SHConfig().is_eocloud_ogc_url() ...
Checks if data source via Sentinel Hub services is available at US West server Example: ``DataSource.LANDSAT8.is_uswest_source()`` or ``DataSource.is_uswest_source(DataSource.LANDSAT8)`` :param self: One of the supported data sources :type self: DataSource :return: ``True`` if data sou...
def is_uswest_source(self): """Checks if data source via Sentinel Hub services is available at US West server Example: ``DataSource.LANDSAT8.is_uswest_source()`` or ``DataSource.is_uswest_source(DataSource.LANDSAT8)`` :param self: One of the supported data sources :type self: DataSourc...
Returns which data sources are available for configured Sentinel Hub OGC URL :return: List of available data sources :rtype: list(sentinelhub.DataSource)
def get_available_sources(cls): """ Returns which data sources are available for configured Sentinel Hub OGC URL :return: List of available data sources :rtype: list(sentinelhub.DataSource) """ if SHConfig().is_eocloud_ogc_url(): return [cls.SENTINEL2_L1C, cls.SENTIN...
Convert from WGS84 to UTM coordinate system :param lng: Longitude :type lng: float :param lat: Latitude :type lat: float :return: UTM coordinates :rtype: tuple
def get_utm_from_wgs84(lng, lat): """ Convert from WGS84 to UTM coordinate system :param lng: Longitude :type lng: float :param lat: Latitude :type lat: float :return: UTM coordinates :rtype: tuple """ _, _, zone, _ = utm.from_latlon(lat, lng) ...
Tests whether CustomUrlParam contains a constant defined with a string `value` :param value: The string representation of the enum constant :type value: str :return: `True` if there exists a constant with a string value `value`, `False` otherwise :rtype: bool
def has_value(cls, value): """ Tests whether CustomUrlParam contains a constant defined with a string `value` :param value: The string representation of the enum constant :type value: str :return: `True` if there exists a constant with a string value `value`, `False` otherwise :...
Canonical extension of file format extension Converts the format extension fmt_ext into the canonical extension for that format. For example, ``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value :param fmt_ext: A string representing an ex...
def canonical_extension(fmt_ext): """ Canonical extension of file format extension Converts the format extension fmt_ext into the canonical extension for that format. For example, ``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value ...
Checks whether file format is an image format Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)`` :param self: File format :type self: MimeType :return: ``True`` if file is in image format, ``False`` otherwise :rtype: bool
def is_image_format(self): """ Checks whether file format is an image format Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)`` :param self: File format :type self: MimeType :return: ``True`` if file is in image format, ``False`` otherwise...
Checks whether file format is a TIFF image format Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)`` :param self: File format :type self: MimeType :return: ``True`` if file is in image format, ``False`` otherwise :rtype: bool
def is_tiff_format(self): """ Checks whether file format is a TIFF image format Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)`` :param self: File format :type self: MimeType :return: ``True`` if file is in image format, ``False`` otherw...
Get file format as string :return: String describing the file format :rtype: str
def get_string(self): """ Get file format as string :return: String describing the file format :rtype: str """ if self in [MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]: return 'image/{}'.format(self.value) if self is MimeType.JP2: retu...
Returns max value of image `MimeType` format and raises an error if it is not an image format Note: For `MimeType.TIFF_d32f` it will return ``1.0`` as that is expected maximum for an image even though it could be higher. :return: A maximum value of specified image format :rtype: int or...
def get_expected_max_value(self): """ Returns max value of image `MimeType` format and raises an error if it is not an image format Note: For `MimeType.TIFF_d32f` it will return ``1.0`` as that is expected maximum for an image even though it could be higher. :return: A maximum value of...
Filters out dates within time_difference, preserving only the oldest date. :param dates: a list of datetime objects :param time_difference: a ``datetime.timedelta`` representing the time difference threshold :return: an ordered list of datetimes `d1<=d2<=...<=dn` such that `d[i+1]-di > time_dif...
def _filter_dates(dates, time_difference): """ Filters out dates within time_difference, preserving only the oldest date. :param dates: a list of datetime objects :param time_difference: a ``datetime.timedelta`` representing the time difference threshold :return: an ordered list...
Checks if Sentinel-1 product ID matches Sentinel-1 DataSource configuration :param product_id: Sentinel-1 product ID :type product_id: str :param data_source: One of the supported Sentinel-1 data sources :type data_source: constants.DataSource :return: True if data_source contai...
def _sentinel1_product_check(product_id, data_source): """Checks if Sentinel-1 product ID matches Sentinel-1 DataSource configuration :param product_id: Sentinel-1 product ID :type product_id: str :param data_source: One of the supported Sentinel-1 data sources :type data_source...
Get download requests Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and acceptable cloud coverage. :param request: QGC-type request with specified bounding box, time interval, and cloud coverage for specific product. ...
def get_request(self, request): """ Get download requests Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and acceptable cloud coverage. :param request: QGC-type request with specified bounding box, time interval, and cloud coverage for ...
Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :param date: acquisition date or None :type dat...
def get_url(self, request, *, date=None, size_x=None, size_y=None, geometry=None): """ Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request...
Creates base url string. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :return: base string for url to Sentinel Hub's OGC service for this product. :rtype: str
def get_base_url(self, request): """ Creates base url string. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :return: base string for url to Sentinel Hub's OGC service for this product. ...
Returns parameters common dictionary for WMS, WCS and FIS request. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :return: dictionary with parameters :rtype: dict
def _get_common_url_parameters(request): """ Returns parameters common dictionary for WMS, WCS and FIS request. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :return: dictionary with param...
Returns parameters common dictionary for WMS and WCS request. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :param date: acquisition date or None :type date: datetime.datetime or None ...
def _get_wms_wcs_url_parameters(request, date): """ Returns parameters common dictionary for WMS and WCS request. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :param date: acquisition dat...
Returns parameters dictionary for FIS request. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :param geometry: list of bounding boxes or geometries :type geometry: list of BBox or Geometry ...
def _get_fis_parameters(request, geometry): """ Returns parameters dictionary for FIS request. :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :param geometry: list of bounding boxes or geome...
Get filename location Returns the filename's location on disk where data is or is going to be stored. The files are stored in the folder specified by the user when initialising OGC-type of request. The name of the file has the following structure: {service_type}_{layer}_{crs}_{bbox}_{t...
def get_filename(request, date, size_x, size_y): """ Get filename location Returns the filename's location on disk where data is or is going to be stored. The files are stored in the folder specified by the user when initialising OGC-type of request. The name of the file has the followi...
Adds custom url parameters to filename string :param filename: Initial filename :type filename: str :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :return: Filename with custom url p...
def filename_add_custom_url_params(filename, request): """ Adds custom url parameters to filename string :param filename: Initial filename :type filename: str :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcReq...
Replaces invalid characters in filename string, adds image extension and reduces filename length :param filename: Incomplete filename string :type filename: str :param file_format: Format which will be used for filename extension :type file_format: MimeType :return: Final filena...
def finalize_filename(filename, file_format=None): """ Replaces invalid characters in filename string, adds image extension and reduces filename length :param filename: Incomplete filename string :type filename: str :param file_format: Format which will be used for filename extension ...
Get available Sentinel-2 acquisitions at least time_difference apart List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified time interval. When a single time is specified the request will return that specific date, if it exists. If a time range is...
def get_dates(self, request): """ Get available Sentinel-2 acquisitions at least time_difference apart List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified time interval. When a single time is specified the request will return that specific date...
Verifies or calculates image dimensions. :param request: OGC-type request :type request: WmsRequest or WcsRequest :return: horizontal and vertical dimensions of requested image :rtype: (int or str, int or str)
def get_image_dimensions(request): """ Verifies or calculates image dimensions. :param request: OGC-type request :type request: WmsRequest or WcsRequest :return: horizontal and vertical dimensions of requested image :rtype: (int or str, int or str) """ if...
Collects data from WFS service :return: dictionary containing info about product tiles :rtype: dict
def _fetch_features(self): """Collects data from WFS service :return: dictionary containing info about product tiles :rtype: dict """ if self.feature_offset is None: return main_url = '{}{}/{}?'.format(self.base_url, ServiceType.WFS.value, self.instance_id) ...
Returns a list of acquisition times from tile info data :return: List of acquisition times in the order returned by WFS service. :rtype: list(datetime.datetime)
def get_dates(self): """ Returns a list of acquisition times from tile info data :return: List of acquisition times in the order returned by WFS service. :rtype: list(datetime.datetime) """ return [datetime.datetime.strptime('{}T{}'.format(tile_info['properties']['date'], ...
Extracts tile name, data and AWS index from tile URL :param tile_url: Location of tile at AWS :type: tile_url: str :return: Tuple in a form (tile_name, date, aws_index) :rtype: (str, str, int)
def _parse_tile_url(tile_url): """ Extracts tile name, data and AWS index from tile URL :param tile_url: Location of tile at AWS :type: tile_url: str :return: Tuple in a form (tile_name, date, aws_index) :rtype: (str, str, int) """ props = tile_url.rsplit('/', 7)...
Get all dates within input start and end date in ISO 8601 format :param start_date: start date in ISO 8601 format :type start_date: str :param end_date: end date in ISO 8601 format :type end_date: str :return: list of dates between start_date and end_date in ISO 8601 format :rtype: list of str
def get_dates_in_range(start_date, end_date): """ Get all dates within input start and end date in ISO 8601 format :param start_date: start date in ISO 8601 format :type start_date: str :param end_date: end date in ISO 8601 format :type end_date: str :return: list of dates between start_date an...
Convert ISO 8601 time format to datetime format This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` :param date: date in ISO 8601 format :type date: str :return: datetime instance :rtype: datetime
def iso_to_datetime(date): """ Convert ISO 8601 time format to datetime format This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` :param date: date in ISO 8601 format :type date: str :return: datetime instance ...
Convert datetime format to ISO 8601 time format This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format, e.g. ``2017-09-14`` :param date: datetime instance to convert :type date: datetime :param only_date: whether to return date only or also time...
def datetime_to_iso(date, only_date=True): """ Convert datetime format to ISO 8601 time format This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format, e.g. ``2017-09-14`` :param date: datetime instance to convert :type date: datetime :param ...
Parse input time/date string into ISO 8601 string :param time_input: time/date to parse :type time_input: str or datetime.date or datetime.datetime :return: parsed string in ISO 8601 format :rtype: str
def parse_time(time_input): """ Parse input time/date string into ISO 8601 string :param time_input: time/date to parse :type time_input: str or datetime.date or datetime.datetime :return: parsed string in ISO 8601 format :rtype: str """ if isinstance(time_input, datetime.date): ret...
Parse input into an interval of two times, specifying start and end time, in ISO 8601 format, for example: ``(2017-01-15:T00:00:00, 2017-01-16:T23:59:59)`` The input time can have the following formats, which will be parsed as: * `YYYY-MM-DD` -> `[YYYY-MM-DD:T00:00:00, YYYY-MM-DD:T23:59:59]` * `YYYY-...
def parse_time_interval(time): """ Parse input into an interval of two times, specifying start and end time, in ISO 8601 format, for example: ``(2017-01-15:T00:00:00, 2017-01-16:T23:59:59)`` The input time can have the following formats, which will be parsed as: * `YYYY-MM-DD` -> `[YYYY-MM-DD:T00:00:...
Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads. \b Examples with Sentinel-2 L1C data: sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_201...
def aws(product, tile, folder, redownload, info, entire, bands, l2a): """Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads. \b Examples with Sentinel-2 L1C data: sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 ...
A helper function which joins click.option functions of each parameter from config.json
def _config_options(func): """ A helper function which joins click.option functions of each parameter from config.json """ for param in SHConfig().get_params()[-1::-1]: func = click.option('--{}'.format(param), param, help='Set new values to configuration parameter "{}"'....
Inspect and configure parameters in your local sentinelhub configuration file \b Example: sentinelhub.config --show sentinelhub.config --instance_id <new instance id> sentinelhub.config --max_download_attempts 5 --download_sleep_time 20 --download_timeout_seconds 120
def config(show, reset, **params): """Inspect and configure parameters in your local sentinelhub configuration file \b Example: sentinelhub.config --show sentinelhub.config --instance_id <new instance id> sentinelhub.config --max_download_attempts 5 --download_sleep_time 20 --download_tim...
Download from custom created URL into custom created file path \b Example: sentinelhub.download http://sentinel-s2-l1c.s3.amazonaws.com/tiles/54/H/VH/2017/4/14/0/metadata.xml home/example.xml
def download(url, filename, redownload): """Download from custom created URL into custom created file path \b Example: sentinelhub.download http://sentinel-s2-l1c.s3.amazonaws.com/tiles/54/H/VH/2017/4/14/0/metadata.xml home/example.xml """ data_folder, filename = filename.rsplit('/', 1) dow...
Every time sentinelhub package is installed entire config.json is overwritten. However this function will check if sentinelhub is already installed and try to copy those parameters from old config.json that are by default set to an empty value (i.e. instance_id, aws_access_key_id and aws_secret_access_key) into...
def update_package_config(): """ Every time sentinelhub package is installed entire config.json is overwritten. However this function will check if sentinelhub is already installed and try to copy those parameters from old config.json that are by default set to an empty value (i.e. instance_id, aws_access_k...
Method that saves configuration parameter changes from instance of SHConfig class to global config class and to `config.json` file. Example of use case ``my_config = SHConfig()`` \n ``my_config.instance_id = '<new instance id>'`` \n ``my_config.save()``
def save(self): """Method that saves configuration parameter changes from instance of SHConfig class to global config class and to `config.json` file. Example of use case ``my_config = SHConfig()`` \n ``my_config.instance_id = '<new instance id>'`` \n ``my_co...
Resets a single parameter :param param: A configuration parameter :type param: str
def _reset_param(self, param): """ Resets a single parameter :param param: A configuration parameter :type param: str """ if param not in self._instance.CONFIG_PARAMS: raise ValueError("Cannot reset unknown parameter '{}'".format(param)) setattr(self, param, ...
Resets configuration class to initial values. Use SHConfig.save() method in order to save this change. :param params: Parameters which will be reset. Parameters can be specified with a list of names, e.g. ``['instance_id', 'aws_access_key_id', 'aws_secret_access_key']``, or as a single name, e.g. ...
def reset(self, params=...): """ Resets configuration class to initial values. Use SHConfig.save() method in order to save this change. :param params: Parameters which will be reset. Parameters can be specified with a list of names, e.g. ``['instance_id', 'aws_access_key_id', 'aws_secre...
Get a dictionary representation of `SHConfig` class :return: A dictionary with configuration parameters :rtype: OrderedDict
def get_config_dict(self): """ Get a dictionary representation of `SHConfig` class :return: A dictionary with configuration parameters :rtype: OrderedDict """ return OrderedDict((prop, getattr(self, prop)) for prop in self._instance.CONFIG_PARAMS)
Calculates width and height in pixels for a given bbox of a given pixel resolution (in meters). The result is rounded to nearest integers :param bbox: bounding box :type bbox: geometry.BBox :param resolution: Resolution of desired image in meters. It can be a single number or a tuple of two numbers - ...
def bbox_to_dimensions(bbox, resolution): """ Calculates width and height in pixels for a given bbox of a given pixel resolution (in meters). The result is rounded to nearest integers :param bbox: bounding box :type bbox: geometry.BBox :param resolution: Resolution of desired image in meters. It ca...
Calculates pixel resolution in meters for a given bbox of a given width and height. :param bbox: bounding box :type bbox: geometry.BBox :param width: width of bounding box in pixels :type width: int :param height: height of bounding box in pixels :type height: int :return: resolution east-w...
def bbox_to_resolution(bbox, width, height): """ Calculates pixel resolution in meters for a given bbox of a given width and height. :param bbox: bounding box :type bbox: geometry.BBox :param width: width of bounding box in pixels :type width: int :param height: height of bounding box in pixels...
Given bounding box and one of the parameters width or height it will return the other parameter that will best fit the bounding box dimensions :param bbox: bounding box :type bbox: geometry.BBox :param width: image width or None if height is unknown :type width: int or None :param height: image...
def get_image_dimension(bbox, width=None, height=None): """ Given bounding box and one of the parameters width or height it will return the other parameter that will best fit the bounding box dimensions :param bbox: bounding box :type bbox: geometry.BBox :param width: image width or None if height ...
Transform bbox into UTM CRS :param bbox: bounding box :type bbox: geometry.BBox :return: bounding box in UTM CRS :rtype: geometry.BBox
def to_utm_bbox(bbox): """ Transform bbox into UTM CRS :param bbox: bounding box :type bbox: geometry.BBox :return: bounding box in UTM CRS :rtype: geometry.BBox """ if CRS.is_utm(bbox.crs): return bbox lng, lat = bbox.middle utm_crs = get_utm_crs(lng, lat, source_crs=bbox.c...
Get UTM coordinates given a bounding box in pixels and a transform :param img_bbox: boundaries of bounding box in pixels as `[row1, col1, row2, col2]` :type img_bbox: list :param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)` :type transform: ...
def get_utm_bbox(img_bbox, transform): """ Get UTM coordinates given a bounding box in pixels and a transform :param img_bbox: boundaries of bounding box in pixels as `[row1, col1, row2, col2]` :type img_bbox: list :param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, ...
Convert WGS84 coordinates to UTM. If UTM CRS is not set it will be calculated automatically. :param lng: longitude in WGS84 system :type lng: float :param lat: latitude in WGS84 system :type lat: float :param utm_crs: UTM coordinate reference system enum constants :type utm_crs: constants.CRS o...
def wgs84_to_utm(lng, lat, utm_crs=None): """ Convert WGS84 coordinates to UTM. If UTM CRS is not set it will be calculated automatically. :param lng: longitude in WGS84 system :type lng: float :param lat: latitude in WGS84 system :type lat: float :param utm_crs: UTM coordinate reference system...
Convert any CRS with (east, north) coordinates to WGS84 :param east: east coordinate :type east: float :param north: north coordinate :type north: float :param crs: CRS enum constants :type crs: constants.CRS :return: latitude and longitude coordinates in WGS84 system :rtype: float, flo...
def to_wgs84(east, north, crs): """ Convert any CRS with (east, north) coordinates to WGS84 :param east: east coordinate :type east: float :param north: north coordinate :type north: float :param crs: CRS enum constants :type crs: constants.CRS :return: latitude and longitude coordinate...
Convert UTM coordinate to image coordinate given a transform :param east: east coordinate of point :type east: float :param north: north coordinate of point :type north: float :param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)` :type...
def utm_to_pixel(east, north, transform, truncate=True): """ Convert UTM coordinate to image coordinate given a transform :param east: east coordinate of point :type east: float :param north: north coordinate of point :type north: float :param transform: georeferencing transform of the image, e...
Convert pixel coordinate to UTM coordinate given a transform :param row: row pixel coordinate :type row: int or float :param column: column pixel coordinate :type column: int or float :param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)` ...
def pixel_to_utm(row, column, transform): """ Convert pixel coordinate to UTM coordinate given a transform :param row: row pixel coordinate :type row: int or float :param column: column pixel coordinate :type column: int or float :param transform: georeferencing transform of the image, e.g. `(x...
Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be calculated it automatically. :param lng: longitude of point :type lng: float :param lat: latitude of point :type lat: float :param transform: georeferencing transform of the image, e....
def wgs84_to_pixel(lng, lat, transform, utm_epsg=None, truncate=True): """ Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be calculated it automatically. :param lng: longitude of point :type lng: float :param lat: latitude of point :...
Get CRS for UTM zone in which (lat, lng) is contained. :param lng: longitude :type lng: float :param lat: latitude :type lat: float :param source_crs: source CRS :type source_crs: constants.CRS :return: CRS of the zone containing the lat,lon point :rtype: constants.CRS
def get_utm_crs(lng, lat, source_crs=CRS.WGS84): """ Get CRS for UTM zone in which (lat, lng) is contained. :param lng: longitude :type lng: float :param lat: latitude :type lat: float :param source_crs: source CRS :type source_crs: constants.CRS :return: CRS of the zone containing the ...
Maps point form src_crs to tgt_crs :param point: a tuple `(x, y)` :type point: (float, float) :param source_crs: source CRS :type source_crs: constants.CRS :param target_crs: target CRS :type target_crs: constants.CRS :return: point in target CRS :rtype: (float, float)
def transform_point(point, source_crs, target_crs): """ Maps point form src_crs to tgt_crs :param point: a tuple `(x, y)` :type point: (float, float) :param source_crs: source CRS :type source_crs: constants.CRS :param target_crs: target CRS :type target_crs: constants.CRS :return: poin...
Returns .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified. :param product_id: original ESA product identification string. Default is ``None`` :type product_id: str :param tile: tuple containing tile name and sensing time/date. Default is ``None`` ...
def get_safe_format(product_id=None, tile=None, entire_product=False, bands=None, data_source=DataSource.SENTINEL2_L1C): """ Returns .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified. :param product_id: original ESA product identification string. Def...