INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Columnwise replaces all NaNs and infs from the DataFrame df_impute with average/ extreme values from the same columns. This is done as follows: Each occurring inf or NaN in df_impute is replaced by | def impute(df_impute):
"""
Columnwise replaces all ``NaNs`` and ``infs`` from the DataFrame `df_impute` with average/extreme values from
the same columns. This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` is replaced by
* ``-inf`` -> ``min``
* ``+inf`` -> ``max``
... |
Replaces all NaNs - infs and + infs from the DataFrame df_impute with 0s. The df_impute will be modified in place. All its columns will be into converted into dtype np. float64. | def impute_dataframe_zero(df_impute):
"""
Replaces all ``NaNs``, ``-infs`` and ``+infs`` from the DataFrame `df_impute` with 0s.
The `df_impute` will be modified in place. All its columns will be into converted into dtype ``np.float64``.
:param df_impute: DataFrame to impute
:type df_impute: pandas... |
Columnwise replaces all NaNs - inf and + inf from the DataFrame df_impute with average/ extreme values from the provided dictionaries. | def impute_dataframe_range(df_impute, col_to_max, col_to_min, col_to_median):
"""
Columnwise replaces all ``NaNs``, ``-inf`` and ``+inf`` from the DataFrame `df_impute` with average/extreme values
from the provided dictionaries.
This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` ... |
Retrieves the finite max min and mean values per column in the DataFrame df and stores them in three dictionaries. Those dictionaries col_to_max col_to_min col_to_median map the columnname to the maximal minimal or median value of that column. | def get_range_values_per_column(df):
"""
Retrieves the finite max, min and mean values per column in the DataFrame `df` and stores them in three
dictionaries. Those dictionaries `col_to_max`, `col_to_min`, `col_to_median` map the columnname to the maximal,
minimal or median value of that column.
If... |
Restrict df_or_dict to those ids contained in index. | def restrict_input_to_index(df_or_dict, column_id, index):
"""
Restrict df_or_dict to those ids contained in index.
:param df_or_dict: a pandas DataFrame or a dictionary.
:type df_or_dict: pandas.DataFrame or dict
:param column_id: it must be present in the pandas DataFrame or in all DataFrames in ... |
Aggregates all ids in column_id from the time series container | def get_ids(df_or_dict, column_id):
"""
Aggregates all ids in column_id from the time series container `
:param df_or_dict: a pandas DataFrame or a dictionary.
:type df_or_dict: pandas.DataFrame or dict
:param column_id: it must be present in the pandas DataFrame or in all DataFrames in the diction... |
Try to transform any given input to the internal representation of time series which is a flat DataFrame ( the first format from see: ref: data - formats - label ). | def _normalize_input_to_internal_representation(timeseries_container, column_id, column_sort, column_kind, column_value):
"""
Try to transform any given input to the internal representation of time series, which is a flat DataFrame
(the first format from see :ref:`data-formats-label`).
This function ca... |
This method creates sub windows of the time series. It rolls the ( sorted ) data frames for each kind and each id separately in the time domain ( which is represented by the sort order of the sort column given by column_sort ). | def roll_time_series(df_or_dict, column_id, column_sort, column_kind, rolling_direction, max_timeshift=None):
"""
This method creates sub windows of the time series. It rolls the (sorted) data frames for each kind and each id
separately in the "time" domain (which is represented by the sort order of the sor... |
Takes a singular time series x and constructs a DataFrame df and target vector y that can be used for a time series forecasting task. | def make_forecasting_frame(x, kind, max_timeshift, rolling_direction):
"""
Takes a singular time series x and constructs a DataFrame df and target vector y that can be used for a time series
forecasting task.
The returned df will contain, for every time stamp in x, the last max_timeshift data points as... |
Check the significance of all features ( columns ) of feature matrix X and return a possibly reduced feature matrix only containing relevant features. | def select_features(X, y, test_for_binary_target_binary_feature=defaults.TEST_FOR_BINARY_TARGET_BINARY_FEATURE,
test_for_binary_target_real_feature=defaults.TEST_FOR_BINARY_TARGET_REAL_FEATURE,
test_for_real_target_binary_feature=defaults.TEST_FOR_REAL_TARGET_BINARY_FEATURE,
... |
Connect to a running TWS or IB gateway application. After the connection is made the client is fully synchronized and ready to serve requests. | def connect(
self, host: str = '127.0.0.1', port: int = 7497,
clientId: int = 1, timeout: float = 2):
"""
Connect to a running TWS or IB gateway application.
After the connection is made the client is fully synchronized
and ready to serve requests.
This m... |
Disconnect from a TWS or IB gateway application. This will clear all session state. | def disconnect(self):
"""
Disconnect from a TWS or IB gateway application.
This will clear all session state.
"""
if not self.client.isConnected():
return
stats = self.client.connectionStats()
self._logger.info(
f'Disconnecting from {self.c... |
Wait on any new update to arrive from the network. | def waitOnUpdate(self, timeout: float = 0) -> bool:
"""
Wait on any new update to arrive from the network.
Args:
timeout: Maximum time in seconds to wait.
If 0 then no timeout is used.
.. note::
A loop with ``waitOnUpdate`` should not be used to ... |
Iterate until condition is met with optional timeout in seconds. The yielded value is that of the condition or False when timed out. | def loopUntil(
self, condition=None, timeout: float = 0) -> Iterator[object]:
"""
Iterate until condition is met, with optional timeout in seconds.
The yielded value is that of the condition or False when timed out.
Args:
condition: Predicate function that is tes... |
List of account values for the given account or of all accounts if account is left blank. | def accountValues(self, account: str = '') -> List[AccountValue]:
"""
List of account values for the given account,
or of all accounts if account is left blank.
Args:
account: If specified, filter for this account name.
"""
if account:
return [v f... |
List of account values for the given account or of all accounts if account is left blank. | def accountSummary(self, account: str = '') -> List[AccountValue]:
"""
List of account values for the given account,
or of all accounts if account is left blank.
This method is blocking on first run, non-blocking after that.
Args:
account: If specified, filter for t... |
List of portfolio items of the default account. | def portfolio(self) -> List[PortfolioItem]:
"""
List of portfolio items of the default account.
"""
account = self.wrapper.accounts[0]
return [v for v in self.wrapper.portfolio[account].values()] |
List of positions for the given account or of all accounts if account is left blank. | def positions(self, account: str = '') -> List[Position]:
"""
List of positions for the given account,
or of all accounts if account is left blank.
Args:
account: If specified, filter for this account name.
"""
if account:
return list(self.wrapper... |
List of subscribed: class:. PnL objects ( profit and loss ) optionally filtered by account and/ or modelCode. | def pnl(self, account='', modelCode='') -> List[PnL]:
"""
List of subscribed :class:`.PnL` objects (profit and loss),
optionally filtered by account and/or modelCode.
The :class:`.PnL` objects are kept live updated.
Args:
account: If specified, filter for this accou... |
List of subscribed: class:. PnLSingle objects ( profit and loss for single positions ). | def pnlSingle(
self, account: str = '', modelCode: str = '',
conId: int = 0) -> List[PnLSingle]:
"""
List of subscribed :class:`.PnLSingle` objects (profit and loss for
single positions).
The :class:`.PnLSingle` objects are kept live updated.
Args:
... |
List of all open order trades. | def openTrades(self) -> List[Trade]:
"""
List of all open order trades.
"""
return [v for v in self.wrapper.trades.values()
if v.orderStatus.status not in OrderStatus.DoneStates] |
List of all orders from this session. | def orders(self) -> List[Order]:
"""
List of all orders from this session.
"""
return list(
trade.order for trade in self.wrapper.trades.values()) |
List of all open orders. | def openOrders(self) -> List[Order]:
"""
List of all open orders.
"""
return [trade.order for trade in self.wrapper.trades.values()
if trade.orderStatus.status not in OrderStatus.DoneStates] |
List of all executions from this session. | def executions(self) -> List[Execution]:
"""
List of all executions from this session.
"""
return list(fill.execution for fill in self.wrapper.fills.values()) |
Get ticker of the given contract. It must have been requested before with reqMktData with the same contract object. The ticker may not be ready yet if called directly after: meth:. reqMktData. | def ticker(self, contract: Contract) -> Ticker:
"""
Get ticker of the given contract. It must have been requested before
with reqMktData with the same contract object. The ticker may not be
ready yet if called directly after :meth:`.reqMktData`.
Args:
contract: Contr... |
Request and return a list of snapshot tickers. The list is returned when all tickers are ready. | def reqTickers(
self, *contracts: List[Contract],
regulatorySnapshot: bool = False) -> List[Ticker]:
"""
Request and return a list of snapshot tickers.
The list is returned when all tickers are ready.
This method is blocking.
Args:
contracts:... |
Fully qualify the given contracts in - place. This will fill in the missing fields in the contract especially the conId. | def qualifyContracts(self, *contracts: List[Contract]) -> List[Contract]:
"""
Fully qualify the given contracts in-place. This will fill in
the missing fields in the contract, especially the conId.
Returns a list of contracts that have been successfully qualified.
This method i... |
Create a limit order that is bracketed by a take - profit order and a stop - loss order. Submit the bracket like: | def bracketOrder(
self, action: str, quantity: float,
limitPrice: float, takeProfitPrice: float,
stopLossPrice: float, **kwargs) -> BracketOrder:
"""
Create a limit order that is bracketed by a take-profit order and
a stop-loss order. Submit the bracket like:
... |
Place the trades in the same One Cancels All ( OCA ) group. | def oneCancelsAll(
orders: List[Order], ocaGroup: str, ocaType: int) -> List[Order]:
"""
Place the trades in the same One Cancels All (OCA) group.
https://interactivebrokers.github.io/tws-api/oca.html
Args:
orders: The orders that are to be placed together.
... |
Retrieve commission and margin impact without actually placing the order. The given order will not be modified in any way. | def whatIfOrder(self, contract: Contract, order: Order) -> OrderState:
"""
Retrieve commission and margin impact without actually
placing the order. The given order will not be modified in any way.
This method is blocking.
Args:
contract: Contract to test.
... |
Place a new order or modify an existing order. Returns a Trade that is kept live updated with status changes fills etc. | def placeOrder(self, contract: Contract, order: Order) -> Trade:
"""
Place a new order or modify an existing order.
Returns a Trade that is kept live updated with
status changes, fills, etc.
Args:
contract: Contract to use for order.
order: The order to b... |
Cancel the order and return the Trade it belongs to. | def cancelOrder(self, order: Order) -> Trade:
"""
Cancel the order and return the Trade it belongs to.
Args:
order: The order to be canceled.
"""
self.client.cancelOrder(order.orderId)
now = datetime.datetime.now(datetime.timezone.utc)
key = self.wrap... |
It is recommended to use: meth:. accountValues instead. | def reqAccountUpdatesMulti(
self, account: str = '', modelCode: str = ''):
"""
It is recommended to use :meth:`.accountValues` instead.
Request account values of multiple accounts and keep updated.
This method is blocking.
Args:
account: If specified, f... |
It is recommended to use: meth:. fills or: meth:. executions instead. | def reqExecutions(
self, execFilter: ExecutionFilter = None) -> List[Fill]:
"""
It is recommended to use :meth:`.fills` or
:meth:`.executions` instead.
Request and return a list a list of fills.
This method is blocking.
Args:
execFilter: If spe... |
Start a subscription for profit and loss events. | def reqPnL(self, account: str, modelCode: str = '') -> PnL:
"""
Start a subscription for profit and loss events.
Returns a :class:`.PnL` object that is kept live updated.
The result can also be queried from :meth:`.pnl`.
https://interactivebrokers.github.io/tws-api/pnl.html
... |
Cancel PnL subscription. | def cancelPnL(self, account, modelCode: str = ''):
"""
Cancel PnL subscription.
Args:
account: Cancel for this account.
modelCode: If specified, cancel for this account model.
"""
key = (account, modelCode)
reqId = self.wrapper.pnlKey2ReqId.pop(ke... |
Start a subscription for profit and loss events for single positions. | def reqPnLSingle(
self, account: str, modelCode: str, conId: int) -> PnLSingle:
"""
Start a subscription for profit and loss events for single positions.
Returns a :class:`.PnLSingle` object that is kept live updated.
The result can also be queried from :meth:`.pnlSingle`.
... |
Cancel PnLSingle subscription for the given account modelCode and conId. | def cancelPnLSingle(
self, account: str, modelCode: str, conId: int):
"""
Cancel PnLSingle subscription for the given account, modelCode
and conId.
Args:
account: Cancel for this account name.
modelCode: Cancel for this account model.
conI... |
Get a list of contract details that match the given contract. If the returned list is empty then the contract is not known ; If the list has multiple values then the contract is ambiguous. | def reqContractDetails(self, contract: Contract) -> List[ContractDetails]:
"""
Get a list of contract details that match the given contract.
If the returned list is empty then the contract is not known;
If the list has multiple values then the contract is ambiguous.
The fully qu... |
Request contract descriptions of contracts that match a pattern. | def reqMatchingSymbols(self, pattern: str) -> List[ContractDescription]:
"""
Request contract descriptions of contracts that match a pattern.
This method is blocking.
https://interactivebrokers.github.io/tws-api/matching_symbols.html
Args:
pattern: The first few le... |
Request price increments rule. | def reqMarketRule(self, marketRuleId: int) -> PriceIncrement:
"""
Request price increments rule.
https://interactivebrokers.github.io/tws-api/minimum_increment.html
Args:
marketRuleId: ID of market rule.
The market rule IDs for a contract can be obtained
... |
Request realtime 5 second bars. | def reqRealTimeBars(
self, contract: Contract, barSize: int,
whatToShow: str, useRTH: bool,
realTimeBarsOptions: List[TagValue] = None) -> RealTimeBarList:
"""
Request realtime 5 second bars.
https://interactivebrokers.github.io/tws-api/realtime_bars.html
... |
Cancel the realtime bars subscription. | def cancelRealTimeBars(self, bars: RealTimeBarList):
"""
Cancel the realtime bars subscription.
Args:
bars: The bar list that was obtained from ``reqRealTimeBars``.
"""
self.client.cancelRealTimeBars(bars.reqId)
self.wrapper.endSubscription(bars) |
Request historical bar data. | def reqHistoricalData(
self, contract: Contract, endDateTime: object,
durationStr: str, barSizeSetting: str,
whatToShow: str, useRTH: bool,
formatDate: int = 1, keepUpToDate: bool = False,
chartOptions: List[TagValue] = None) -> BarDataList:
"""
... |
Cancel the update subscription for the historical bars. | def cancelHistoricalData(self, bars: BarDataList):
"""
Cancel the update subscription for the historical bars.
Args:
bars: The bar list that was obtained from ``reqHistoricalData``
with a keepUpToDate subscription.
"""
self.client.cancelHistoricalDat... |
Request historical ticks. The time resolution of the ticks is one second. | def reqHistoricalTicks(
self, contract: Contract,
startDateTime: Union[str, datetime.date],
endDateTime: Union[str, datetime.date],
numberOfTicks: int, whatToShow: str, useRth: bool,
ignoreSize: bool = False,
miscOptions: List[TagValue] = None) -> ... |
Get the datetime of earliest available historical data for the contract. | def reqHeadTimeStamp(
self, contract: Contract, whatToShow: str,
useRTH: bool, formatDate: int = 1) -> datetime.datetime:
"""
Get the datetime of earliest available historical data
for the contract.
Args:
contract: Contract of interest.
us... |
Subscribe to tick data or request a snapshot. Returns the Ticker that holds the market data. The ticker will initially be empty and gradually ( after a couple of seconds ) be filled. | def reqMktData(
self, contract: Contract, genericTickList: str = '',
snapshot: bool = False, regulatorySnapshot: bool = False,
mktDataOptions: List[TagValue] = None) -> Ticker:
"""
Subscribe to tick data or request a snapshot.
Returns the Ticker that holds the... |
Unsubscribe from realtime streaming tick data. | def cancelMktData(self, contract: Contract):
"""
Unsubscribe from realtime streaming tick data.
Args:
contract: The exact contract object that was used to
subscribe with.
"""
ticker = self.ticker(contract)
reqId = self.wrapper.endTicker(ticker... |
Subscribe to tick - by - tick data and return the Ticker that holds the ticks in ticker. tickByTicks. | def reqTickByTickData(
self, contract: Contract, tickType: str,
numberOfTicks: int = 0, ignoreSize: bool = False) -> Ticker:
"""
Subscribe to tick-by-tick data and return the Ticker that
holds the ticks in ticker.tickByTicks.
https://interactivebrokers.github.io/... |
Unsubscribe from tick - by - tick data | def cancelTickByTickData(self, contract: Contract, tickType: str):
"""
Unsubscribe from tick-by-tick data
Args:
contract: The exact contract object that was used to
subscribe with.
"""
ticker = self.ticker(contract)
reqId = self.wrapper.endTic... |
Subscribe to market depth data ( a. k. a. DOM L2 or order book ). | def reqMktDepth(
self, contract: Contract, numRows: int = 5,
isSmartDepth: bool = False, mktDepthOptions=None) -> Ticker:
"""
Subscribe to market depth data (a.k.a. DOM, L2 or order book).
https://interactivebrokers.github.io/tws-api/market_depth.html
Args:
... |
Unsubscribe from market depth data. | def cancelMktDepth(self, contract: Contract, isSmartDepth=False):
"""
Unsubscribe from market depth data.
Args:
contract: The exact contract object that was used to
subscribe with.
"""
ticker = self.ticker(contract)
reqId = self.wrapper.endTic... |
Request histogram data. | def reqHistogramData(
self, contract: Contract,
useRTH: bool, period: str) -> List[HistogramData]:
"""
Request histogram data.
This method is blocking.
https://interactivebrokers.github.io/tws-api/histograms.html
Args:
contract: Contract to ... |
Get fundamental data of a contract in XML format. | def reqFundamentalData(
self, contract: Contract, reportType: str,
fundamentalDataOptions: List[TagValue] = None) -> str:
"""
Get fundamental data of a contract in XML format.
This method is blocking.
https://interactivebrokers.github.io/tws-api/fundamentals.htm... |
Do a blocking market scan by starting a subscription and canceling it after the initial list of results are in. | def reqScannerData(
self, subscription: ScannerSubscription,
scannerSubscriptionOptions: List[TagValue] = None,
scannerSubscriptionFilterOptions:
List[TagValue] = None) -> ScanDataList:
"""
Do a blocking market scan by starting a subscription and canceling... |
Subscribe to market scan data. | def reqScannerSubscription(
self, subscription: ScannerSubscription,
scannerSubscriptionOptions: List[TagValue] = None,
scannerSubscriptionFilterOptions:
List[TagValue] = None) -> ScanDataList:
"""
Subscribe to market scan data.
https://interactiv... |
Cancel market data subscription. | def cancelScannerSubscription(self, dataList: ScanDataList):
"""
Cancel market data subscription.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Args:
dataList: The scan data list that was obtained from
:meth:`.reqScannerSubscription`.
... |
Calculate the volatility given the option price. | def calculateImpliedVolatility(
self, contract: Contract,
optionPrice: float, underPrice: float,
implVolOptions: List[TagValue] = None) -> OptionComputation:
"""
Calculate the volatility given the option price.
This method is blocking.
https://intera... |
Calculate the option price given the volatility. | def calculateOptionPrice(
self, contract: Contract,
volatility: float, underPrice: float,
optPrcOptions=None) -> OptionComputation:
"""
Calculate the option price given the volatility.
This method is blocking.
https://interactivebrokers.github.io/tws... |
Get the option chain. | def reqSecDefOptParams(
self, underlyingSymbol: str,
futFopExchange: str, underlyingSecType: str,
underlyingConId: int) -> List[OptionChain]:
"""
Get the option chain.
This method is blocking.
https://interactivebrokers.github.io/tws-api/options.html... |
Exercise an options contract. | def exerciseOptions(
self, contract: Contract, exerciseAction: int,
exerciseQuantity: int, account: str, override: int):
"""
Exercise an options contract.
https://interactivebrokers.github.io/tws-api/options.html
Args:
contract: The option contract t... |
Get the body of a news article. | def reqNewsArticle(
self, providerCode: str, articleId: str,
newsArticleOptions: List[TagValue] = None) -> NewsArticle:
"""
Get the body of a news article.
This method is blocking.
https://interactivebrokers.github.io/tws-api/news.html
Args:
... |
Get historical news headline. | def reqHistoricalNews(
self, conId: int, providerCodes: str,
startDateTime: Union[str, datetime.date],
endDateTime: Union[str, datetime.date],
totalResults: int,
historicalNewsOptions: List[TagValue] = None) -> HistoricalNews:
"""
Get historica... |
Replaces Financial Advisor s settings. | def replaceFA(self, faDataType: int, xml: str):
"""
Replaces Financial Advisor's settings.
Args:
faDataType: See :meth:`.requestFA`.
xml: The XML-formatted configuration string.
"""
self.client.replaceFA(faDataType, xml) |
Create pandas DataFrame from the sequence of same - type objects. When a list of labels is given then only retain those labels and drop the rest. | def df(objs, labels=None):
"""
Create pandas DataFrame from the sequence of same-type objects.
When a list of labels is given then only retain those labels and
drop the rest.
"""
import pandas as pd
from .objects import Object, DynamicObject
if objs:
objs = list(objs)
obj... |
Convert object to a tree of lists dicts and simple values. The result can be serialized to JSON. | def tree(obj):
"""
Convert object to a tree of lists, dicts and simple values.
The result can be serialized to JSON.
"""
from .objects import Object
if isinstance(obj, (bool, int, float, str, bytes)):
return obj
elif isinstance(obj, (datetime.date, datetime.time)):
return obj... |
Create candlestick plot for the given bars. The bars can be given as a DataFrame or as a list of bar objects. | def barplot(bars, title='', upColor='blue', downColor='red'):
"""
Create candlestick plot for the given bars. The bars can be given as
a DataFrame or as a list of bar objects.
"""
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patc... |
Create a log handler that logs to the given file. | def logToFile(path, level=logging.INFO):
"""
Create a log handler that logs to the given file.
"""
logger = logging.getLogger()
logger.setLevel(level)
formatter = logging.Formatter(
'%(asctime)s %(name)s %(levelname)s %(message)s')
handler = logging.FileHandler(path)
handler.setF... |
Create a log handler that logs to the console. | def logToConsole(level=logging.INFO):
"""
Create a log handler that logs to the console.
"""
logger = logging.getLogger()
logger.setLevel(level)
formatter = logging.Formatter(
'%(asctime)s %(name)s %(levelname)s %(message)s')
handler = logging.StreamHandler()
handler.setFormatter... |
Format the integer or float n to 3 significant digits + SI prefix. | def formatSI(n) -> str:
"""
Format the integer or float n to 3 significant digits + SI prefix.
"""
s = ''
if n < 0:
n = -n
s += '-'
if type(n) is int and n < 1000:
s = str(n) + ' '
elif n < 1e-22:
s = '0.00 '
else:
assert n < 9.99e26
log = ... |
By default run the event loop forever. | def run(*awaitables, timeout: float = None):
"""
By default run the event loop forever.
When awaitables (like Tasks, Futures or coroutines) are given then
run the event loop until each has completed and return their results.
An optional timeout (in seconds) can be given that will raise
asyncio... |
Schedule the callback to be run at the given time with the given arguments. | def schedule(
time: Union[datetime.time, datetime.datetime],
callback: Callable, *args):
"""
Schedule the callback to be run at the given time with
the given arguments.
Args:
time: Time to run callback. If given as :py:class:`datetime.time`
then use today as date.
... |
Iterator that waits periodically until certain time points are reached while yielding those time points. | def timeRange(
start: datetime.time, end: datetime.time,
step: float) -> Iterator[datetime.datetime]:
"""
Iterator that waits periodically until certain time points are
reached while yielding those time points.
Args:
start: Start time, can be specified as datetime.datetime,
... |
Async version of: meth: timeRange. | async def timeRangeAsync(
start: datetime.time, end: datetime.time,
step: float) -> AsyncIterator[datetime.datetime]:
"""
Async version of :meth:`timeRange`.
"""
assert step > 0
start = _fillDate(start)
end = _fillDate(end)
delta = datetime.timedelta(seconds=step)
t = sta... |
Async version of: meth: waitUntil. | async def waitUntilAsync(t: datetime.time) -> bool:
"""
Async version of :meth:`waitUntil`.
"""
t = _fillDate(t)
now = datetime.datetime.now(t.tzinfo)
secs = (t - now).total_seconds()
await asyncio.sleep(secs)
return True |
Use nested asyncio event loop for Jupyter notebooks. | def startLoop():
"""
Use nested asyncio event loop for Jupyter notebooks.
"""
def _ipython_loop_asyncio(kernel):
'''
Use asyncio event loop for the given IPython kernel.
'''
loop = asyncio.get_event_loop()
def kernel_handler():
kernel.do_one_iteration... |
Run combined Qt5/ asyncio event loop. | def useQt(qtLib: str = 'PyQt5', period: float = 0.01):
"""
Run combined Qt5/asyncio event loop.
Args:
qtLib: Name of Qt library to use, can be 'PyQt5' or 'PySide2'.
period: Period in seconds to poll Qt.
"""
def qt_step():
loop.call_later(period, qt_step)
if not stack... |
Format date or datetime to string that IB uses. | def formatIBDatetime(dt) -> str:
"""
Format date or datetime to string that IB uses.
"""
if not dt:
s = ''
elif isinstance(dt, datetime.datetime):
if dt.tzinfo:
# convert to local system timezone
dt = dt.astimezone()
s = dt.strftime('%Y%m%d %H:%M:%S')
... |
Parse string in IB date or datetime format to datetime. | def parseIBDatetime(s):
"""
Parse string in IB date or datetime format to datetime.
"""
if len(s) == 8:
# YYYYmmdd
y = int(s[0:4])
m = int(s[4:6])
d = int(s[6:8])
dt = datetime.date(y, m, d)
elif s.isdigit():
dt = datetime.datetime.fromtimestamp(
... |
Return values as a tuple. | def tuple(self):
"""
Return values as a tuple.
"""
return tuple(getattr(self, k) for k in self.__class__.defaults) |
Return key - value pairs as a dictionary. | def dict(self):
"""
Return key-value pairs as a dictionary.
"""
return {k: getattr(self, k) for k in self.__class__.defaults} |
Return differences between self and other as dictionary of 2 - tuples. | def diff(self, other):
"""
Return differences between self and other as dictionary of 2-tuples.
"""
diff = {}
for k in self.__class__.defaults:
left = getattr(self, k)
right = getattr(other, k)
if left != right:
diff[k] = (left,... |
Get a dictionary of all attributes that differ from the default. | def nonDefaults(self):
"""
Get a dictionary of all attributes that differ from the default.
"""
nonDefaults = {}
for k, d in self.__class__.defaults.items():
v = getattr(self, k)
if v != d and (v == v or d == d): # tests for NaN too
nonDef... |
Start a new request and return the future that is associated with with the key and container. The container is a list by default. | def startReq(self, key, contract=None, container=None):
"""
Start a new request and return the future that is associated
with with the key and container. The container is a list by default.
"""
future = asyncio.Future()
self._futures[key] = future
self._results[ke... |
Finish the future of corresponding key with the given result. If no result is given then it will be popped of the general results. | def _endReq(self, key, result=None, success=True):
"""
Finish the future of corresponding key with the given result.
If no result is given then it will be popped of the general results.
"""
future = self._futures.pop(key, None)
self._reqId2Contract.pop(key, None)
... |
Start a tick request that has the reqId associated with the contract. Return the ticker. | def startTicker(self, reqId, contract, tickType):
"""
Start a tick request that has the reqId associated with the contract.
Return the ticker.
"""
ticker = self.tickers.get(id(contract))
if not ticker:
ticker = Ticker(
contract=contract, ticks=... |
Register a live subscription. | def startSubscription(self, reqId, subscriber, contract=None):
"""
Register a live subscription.
"""
self._reqId2Contract[reqId] = contract
self.reqId2Subscriber[reqId] = subscriber |
Unregister a live subscription. | def endSubscription(self, subscriber):
"""
Unregister a live subscription.
"""
self._reqId2Contract.pop(subscriber.reqId, None)
self.reqId2Subscriber.pop(subscriber.reqId, None) |
This wrapper is called to: | def openOrder(self, orderId, contract, order, orderState):
"""
This wrapper is called to:
* feed in open orders at startup;
* feed in open orders or order updates from other clients and TWS
if clientId=master id;
* feed in manual orders and order updates from TWS if cl... |
This wrapper handles both live fills and responses to reqExecutions. | def execDetails(self, reqId, contract, execution):
"""
This wrapper handles both live fills and responses to reqExecutions.
"""
if execution.orderId == UNSET_INTEGER:
# bug in TWS: executions of manual orders have unset value
execution.orderId = 0
key = se... |
Get statistics about the connection. | def connectionStats(self) -> ConnectionStats:
"""
Get statistics about the connection.
"""
if not self.isReady():
raise ConnectionError('Not connected')
return ConnectionStats(
self._startTime,
time.time() - self._startTime,
self._n... |
Get new request ID. | def getReqId(self) -> int:
"""
Get new request ID.
"""
if not self.isReady():
raise ConnectionError('Not connected')
newId = self._reqIdSeq
self._reqIdSeq += 1
return newId |
Disconnect from IB connection. | def disconnect(self):
"""
Disconnect from IB connection.
"""
self.connState = Client.DISCONNECTED
if self.conn is not None:
self._logger.info('Disconnecting')
self.conn.disconnect()
self.wrapper.connectionClosed()
self.reset() |
Serialize and send the given fields using the IB socket protocol. | def send(self, *fields):
"""
Serialize and send the given fields using the IB socket protocol.
"""
if not self.isConnected():
raise ConnectionError('Not connected')
msg = io.StringIO()
for field in fields:
typ = type(field)
if field in... |
Create a message handler that invokes a wrapper method with the in - order message fields as parameters skipping over the first skip fields and parsed according to the types list. | def wrap(self, methodName, types, skip=2):
"""
Create a message handler that invokes a wrapper method
with the in-order message fields as parameters, skipping over
the first ``skip`` fields, and parsed according to the ``types`` list.
"""
def handler(fields):
... |
Decode fields and invoke corresponding wrapper method. | def interpret(self, fields):
"""
Decode fields and invoke corresponding wrapper method.
"""
try:
msgId = int(fields[0])
handler = self.handlers[msgId]
handler(fields)
except Exception:
self.logger.exception(f'Error handling fields: ... |
Parse the object s properties according to its default types. | def parse(self, obj):
"""
Parse the object's properties according to its default types.
"""
for k, default in obj.__class__.defaults.items():
typ = type(default)
if typ is str:
continue
v = getattr(obj, k)
if typ is int:
... |
Get the set of topics that can be extracted from this report. | def topics(self):
"""
Get the set of topics that can be extracted from this report.
"""
return set(node.tag for node in self.root.iter() if node.attrib) |
Extract items of given topic and return as list of objects. | def extract(self, topic: str, parseNumbers=True) -> list:
"""
Extract items of given topic and return as list of objects.
The topic is a string like TradeConfirm, ChangeInDividendAccrual,
Order, etc.
"""
cls = type(topic, (DynamicObject,), {})
results = [cls(**no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.