INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Tests connection to a tcp port and tries to establish a three way handshake. To be used for network discovery or testing.
def tcp_ping( task: Task, ports: List[int], timeout: int = 2, host: Optional[str] = None ) -> Result: """ Tests connection to a tcp port and tries to establish a three way handshake. To be used for network discovery or testing. Arguments: ports (list of int): tcp ports to ping timeo...
Gather information from network devices using napalm
def napalm_get( task: Task, getters: List[str], getters_options: GetterOptionsDict = None, **kwargs: Any ) -> Result: """ Gather information from network devices using napalm Arguments: getters: getters to use getters_options (dict of dicts): When passing multiple getters yo...
Executes a command remotely on the host
def remote_command(task: Task, command: str) -> Result: """ Executes a command remotely on the host Arguments: command (``str``): command to execute Returns: Result object with the following attributes set: * result (``str``): stderr or stdout * stdout (``str``): st...
Connect to the device and populate the attribute: attr: connection with the underlying connection
def open( self, hostname: Optional[str], username: Optional[str], password: Optional[str], port: Optional[int], platform: Optional[str], extras: Optional[Dict[str, Any]] = None, configuration: Optional[Config] = None, ) -> None: """ Con...
Registers a connection plugin with a specified name
def register(cls, name: str, plugin: Type[ConnectionPlugin]) -> None: """Registers a connection plugin with a specified name Args: name: name of the connection plugin to register plugin: defined connection plugin class Raises: :obj:`nornir.core.exceptions.Co...
Deregisters a registered connection plugin by its name
def deregister(cls, name: str) -> None: """Deregisters a registered connection plugin by its name Args: name: name of the connection plugin to deregister Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` """ if name not in cls.available...
Fetches the connection plugin by name if already registered
def get_plugin(cls, name: str) -> Type[ConnectionPlugin]: """Fetches the connection plugin by name if already registered Args: name: name of the connection plugin Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` """ if name not in cls....
Arguments: config_file ( str ): Path to the configuration file ( optional ) dry_run ( bool ): Whether to simulate changes or not configure_logging: Whether to configure logging or not. This argument is being deprecated. Please use logging. enabled parameter in the configuration instead. ** kwargs: Extra information to ...
def InitNornir( config_file: str = "", dry_run: bool = False, configure_logging: Optional[bool] = None, **kwargs: Dict[str, Any], ) -> Nornir: """ Arguments: config_file(str): Path to the configuration file (optional) dry_run(bool): Whether to simulate changes or not conf...
Write contents to a file ( locally )
def write_file( task: Task, filename: str, content: str, append: bool = False, dry_run: Optional[bool] = None, ) -> Result: """ Write contents to a file (locally) Arguments: dry_run: Whether to apply changes or not filename: file you want to write into content: c...
Parse command line arguments and return only the non - default ones
def load_cli_args(self): """ Parse command line arguments and return only the non-default ones :Retruns: dict a dict of any non-default args passed on the command-line. """ parser = argparse.ArgumentParser(description='QTPyLib Reporting', ...
Starts the reporting module
def run(self): """Starts the reporting module Makes the dashboard web app available via localhost:port, and exposes a REST API for trade information, open positions and market data. """ # ----------------------------------- # assign view app.add_url_rule('/', 'i...
add instruments after initialization
def add_instruments(self, *instruments): """ add instruments after initialization """ for instrument in instruments: if isinstance(instrument, ezibpy.utils.Contract): instrument = self.ibConn.contract_to_tuple(instrument) contractString = self.ibConn.contractS...
add contracts to groups
def register_combo(self, parent, legs): """ add contracts to groups """ parent = self.ibConn.contractString(parent) legs_dict = {} for leg in legs: leg = self.ibConn.contractString(leg) legs_dict[leg] = self.get_instrument(leg) self.instrument_combos[paren...
get group by child symbol
def get_combo(self, symbol): """ get group by child symbol """ for parent, legs in self.instrument_combos.items(): if symbol == parent or symbol in legs.keys(): return { "parent": self.get_instrument(parent), "legs": legs, ...
constructs trade info from order data
def _register_trade(self, order): """ constructs trade info from order data """ if order['id'] in self.orders.recent: orderId = order['id'] else: orderId = order['parentId'] # entry / exit? symbol = order["symbol"] order_data = self.orders.recent[o...
cancel child orders when parent is gone
def _cancel_orphan_orders(self, orderId): """ cancel child orders when parent is gone """ orders = self.ibConn.orders for order in orders: order = orders[order] if order['parentId'] != orderId: self.ibConn.cancelOrder(order['id'])
expires pending orders
def _cancel_expired_pending_orders(self): """ expires pending orders """ # use a copy to prevent errors pending = self.orders.pending.copy() for symbol in pending: orderId = pending[symbol]["orderId"] expiration = pending[symbol]["expires"] delta = ex...
A string subclass that provides easy access to misc symbol - related methods and information using shorthand. Refer to the Instruments API <#instrument - api > _ for available methods and properties
def get_instrument(self, symbol): """ A string subclass that provides easy access to misc symbol-related methods and information using shorthand. Refer to the `Instruments API <#instrument-api>`_ for available methods and properties Call from within your strategy: ...
Start the recurring task.
def run(self): """Start the recurring task.""" if self.init_sec: sleep(self.init_sec) self._functime = time() while self._running: start = time() self._func() self._functime += self.interval_sec if self._functime - start > 0: ...
Load running blotter s settings ( used by clients )
def load_blotter_args(blotter_name=None, logger=None): """ Load running blotter's settings (used by clients) :Parameters: blotter_name : str Running Blotter's name (defaults to "auto-detect") logger : object Logger to be use (defaults to Blotter's) :Returns: ...
Retrives symbol s ID from the Database or create it if it doesn t exist
def get_symbol_id(symbol, dbconn, dbcurr, ibConn=None): """ Retrives symbol's ID from the Database or create it if it doesn't exist :Parameters: symbol : str Instrument symbol dbconn : object Database connection to be used dbcurr : object Database...
Starts the blotter
def run(self): """Starts the blotter Connects to the TWS/GW, processes and logs market data, and broadcast it over TCP via ZeroMQ (which algo subscribe to) """ self._check_unique_blotter() # connect to mysql self.mysql_connect() self.context = zmq.Cont...
fix out - of - sequence ticks/ bars
def _fix_history_sequence(self, df, table): """ fix out-of-sequence ticks/bars """ # remove "Unnamed: x" columns cols = df.columns[df.columns.str.startswith('Unnamed:')].tolist() df.drop(cols, axis=1, inplace=True) # remove future dates df['datetime'] = pd.to_datetime(d...
Backfills missing historical data
def backfill(self, data, resolution, start, end=None): """ Backfills missing historical data :Optional: data : pd.DataFrame Minimum required bars for backfill attempt resolution : str Algo resolution start: datetime ...
remove previous globex day from df
def session(df, start='17:00', end='16:00'): """ remove previous globex day from df """ if df.empty: return df # get start/end/now as decimals int_start = list(map(int, start.split(':'))) int_start = (int_start[0] + int_start[1] - 1 / 100) - 0.0001 int_end = list(map(int, end.split(':')...
Internal bar strength
def ibs(bars): """ Internal bar strength """ res = np.round((bars['close'] - bars['low']) / (bars['high'] - bars['low']), 2) return pd.Series(index=bars.index, data=res)
calculate vwap of entire time series ( input can be pandas series or numpy array ) bars are usually mid [ ( h + l )/ 2 ] or typical [ ( h + l + c )/ 3 ]
def vwap(bars): """ calculate vwap of entire time series (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] """ typical = ((bars['high'] + bars['low'] + bars['close']) / 3).values volume = bars['volume'].values return pd.Series(index=ba...
calculate vwap using moving window ( input can be pandas series or numpy array ) bars are usually mid [ ( h + l )/ 2 ] or typical [ ( h + l + c )/ 3 ]
def rolling_vwap(bars, window=200, min_periods=None): """ calculate vwap using moving window (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] """ min_periods = window if min_periods is None else min_periods typical = ((bars['high'] + bars...
compute the n period relative strength indicator
def rsi(series, window=14): """ compute the n period relative strength indicator """ # 100-(100/relative_strength) deltas = np.diff(series) seed = deltas[:window + 1] # default values ups = seed[seed > 0].sum() / window downs = -seed[seed < 0].sum() / window rsival = np.zeros_l...
compute the MACD ( Moving Average Convergence/ Divergence ) using a fast and slow exponential moving avg return value is emaslow emafast macd which are len ( x ) arrays
def macd(series, fast=3, slow=10, smooth=16): """ compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg' return value is emaslow, emafast, macd which are len(x) arrays """ macd_line = rolling_weighted_mean(series, window=fast) - \ rolling_w...
compute rate of change
def roc(series, window=14): """ compute rate of change """ res = (series - series.shift(window)) / series.shift(window) return pd.Series(index=series.index, data=res)
compute commodity channel index
def cci(series, window=14): """ compute commodity channel index """ price = typical_price(series) typical_mean = rolling_mean(price, window) res = (price - typical_mean) / (.015 * np.std(typical_mean)) return pd.Series(index=series.index, data=res)
compute the n period relative strength indicator http:// excelta. blogspot. co. il/ 2013/ 09/ stochastic - oscillator - technical. html
def stoch(df, window=14, d=3, k=3, fast=False): """ compute the n period relative strength indicator http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html """ my_df = pd.DataFrame(index=df.index) my_df['rolling_max'] = df['high'].rolling(window).max() my_df['rolling_mi...
John Ehlers Zero lag ( exponential ) moving average https:// en. wikipedia. org/ wiki/ Zero_lag_exponential_moving_average
def zlma(series, window=20, min_periods=None, kind="ema"): """ John Ehlers' Zero lag (exponential) moving average https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average """ min_periods = window if min_periods is None else min_periods lag = (window - 1) // 2 series = 2 * series - ...
get zscore of price
def zscore(bars, window=20, stds=1, col='close'): """ get zscore of price """ std = numpy_rolling_std(bars[col], window) mean = numpy_rolling_mean(bars[col], window) return (bars[col] - mean) / (std * stds)
Price Volume Trend
def pvt(bars): """ Price Volume Trend """ trend = ((bars['close'] - bars['close'].shift(1)) / bars['close'].shift(1)) * bars['volume'] return trend.cumsum()
Starts the algo
def run(self): """Starts the algo Connects to the Blotter, processes market data and passes tick data to the ``on_tick`` function and bar data to the ``on_bar`` methods. """ history = pd.DataFrame() # get history from csv dir if self.backtest and self.b...
Get historical market data. Connects to Blotter and gets historical data from storage
def get_history(self, symbols, start, end=None, resolution="1T", tz="UTC"): """Get historical market data. Connects to Blotter and gets historical data from storage :Parameters: symbols : list List of symbols to fetch history for start : datetime / string...
Send an order for the selected instrument
def order(self, signal, symbol, quantity=0, **kwargs): """ Send an order for the selected instrument :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) symbol : string instrument symbol quantity : int ...
Records data for later analysis. Values will be logged to the file specified via -- output [ file ] ( along with bar data ) as csv/ pickle/ h5 file.
def record(self, *args, **kwargs): """Records data for later analysis. Values will be logged to the file specified via ``--output [file]`` (along with bar data) as csv/pickle/h5 file. Call from within your strategy: ``self.record(key=value)`` :Parameters: ...
Sends an SMS message. Relies on properly setting up an SMS provider ( refer to the SMS section of the documentation for more information about this )
def sms(self, text): """Sends an SMS message. Relies on properly setting up an SMS provider (refer to the SMS section of the documentation for more information about this) Call from within your strategy: ``self.sms("message text")`` :Parameters: text : strin...
non threaded bar handler ( called by threaded _tick_handler )
def _base_bar_handler(self, bar): """ non threaded bar handler (called by threaded _tick_handler) """ # bar symbol symbol = bar['symbol'].values if len(symbol) == 0: return symbol = symbol[0] self_bars = self.bars.copy() # work on copy is_tick_or_vol...
Initilize signal history
def _add_signal_history(self, df, symbol): """ Initilize signal history """ if symbol not in self.signals.keys() or len(self.signals[symbol]) == 0: self.signals[symbol] = [nan] * len(df.index) else: self.signals[symbol].append(nan) self.signals[symbol] = self.sig...
get last N rows RELATIVE to another row in pandas http:// stackoverflow. com/ questions/ 25724056/ how - to - get - last - n - rows - relative - to - another - row - in - pandas - vector - solution
def multi_shift(df, window): """ get last N rows RELATIVE to another row in pandas http://stackoverflow.com/questions/25724056/how-to-get-last-n-rows-relative-to-another-row-in-pandas-vector-solution """ if isinstance(df, pd.Series): df = pd.DataFrame(df) dfs = [df.shift(i) for i in np....
checks if a string is a number ( int/ float )
def is_number(string): """ checks if a string is a number (int/float) """ string = str(string) if string.isnumeric(): return True try: float(string) return True except ValueError: return False
convert datatypes into Decimals
def to_decimal(number, points=None): """ convert datatypes into Decimals """ if not is_number(number): return number number = float(decimal.Decimal(number * 1.)) # can't Decimal an int if is_number(points): return round(number, points) return number
create ib contract tuple
def create_ib_tuple(instrument): """ create ib contract tuple """ from qtpylib import futures if isinstance(instrument, str): instrument = instrument.upper() if "FUT." not in instrument: # symbol stock instrument = (instrument, "STK", "SMART", "USD", "", 0.0, "") ...
change mod to writeable
def chmod(f): """ change mod to writeable """ try: os.chmod(f, S_IWRITE) # windows (cover all) except Exception as e: pass try: os.chmod(f, 0o777) # *nix except Exception as e: pass
converts df to dict and adds a datetime field if df is datetime
def as_dict(df, ix=':'): """ converts df to dict and adds a datetime field if df is datetime """ if isinstance(df.index, pd.DatetimeIndex): df['datetime'] = df.index return df.to_dict(orient='records')[ix]
Get a datetime object or a epoch timestamp and return an IB - compatible durationStr for reqHistoricalData ()
def ib_duration_str(start_date=None): """ Get a datetime object or a epoch timestamp and return an IB-compatible durationStr for reqHistoricalData() """ now = datetime.datetime.utcnow() if is_number(start_date): diff = now - datetime.datetime.fromtimestamp(float(start_date)) elif is...
convert numpy s datetime64 to datetime
def datetime64_to_datetime(dt): """ convert numpy's datetime64 to datetime """ dt64 = np.datetime64(dt) ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's') return datetime.datetime.utcfromtimestamp(ts)
round to closest resolution
def round_to_fraction(val, res, decimals=None): """ round to closest resolution """ if val is None: return 0.0 if decimals is None and "." in str(res): decimals = len(str(res).split('.')[1]) return round(round(val / res) * res, decimals)
get past date based on currect date
def backdate(res, date=None, as_datetime=False, fmt='%Y-%m-%d'): """ get past date based on currect date """ if res is None: return None if date is None: date = datetime.datetime.now() else: try: date = parse_date(date) except Exception as e: pass...
get the most recent business day
def previous_weekday(day=None, as_datetime=False): """ get the most recent business day """ if day is None: day = datetime.datetime.now() else: day = datetime.datetime.strptime(day, '%Y-%m-%d') day -= datetime.timedelta(days=1) while day.weekday() > 4: # Mon-Fri are 0-4 day...
check if day is month s 3rd friday
def is_third_friday(day=None): """ check if day is month's 3rd friday """ day = day if day is not None else datetime.datetime.now() defacto_friday = (day.weekday() == 4) or ( day.weekday() == 3 and day.hour() >= 17) return defacto_friday and 14 < day.day < 22
check if day is after month s 3rd friday
def after_third_friday(day=None): """ check if day is after month's 3rd friday """ day = day if day is not None else datetime.datetime.now() now = day.replace(day=1, hour=16, minute=0, second=0, microsecond=0) now += relativedelta.relativedelta(weeks=2, weekday=relativedelta.FR) return day > now
utility to get the machine s timezone
def get_timezone(as_timedelta=False): """ utility to get the machine's timezone """ try: offset_hour = -(time.altzone if time.daylight else time.timezone) except Exception as e: offset_hour = -(datetime.datetime.now() - datetime.datetime.utcnow()).seconds offset_...
convert naive datetime to timezone - aware datetime
def datetime_to_timezone(date, tz="UTC"): """ convert naive datetime to timezone-aware datetime """ if not date.tzinfo: date = date.replace(tzinfo=timezone(get_timezone())) return date.astimezone(timezone(tz))
get timezone as tz_offset
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None): """ get timezone as tz_offset """ tz_offset = datetime_to_timezone( datetime.datetime.now(), tz=tz_from).strftime('%z') tz_offset = tz_offset[:3] + ':' + tz_offset[3:] date = parse_date(str(date_str) + tz_offset) if tz_from != ...
change the timeozone to specified one without converting
def set_timezone(data, tz=None, from_local=False): """ change the timeozone to specified one without converting """ # pandas object? if isinstance(data, pd.DataFrame) | isinstance(data, pd.Series): try: try: data.index = data.index.tz_convert(tz) except Except...
set timezone for pandas
def fix_timezone(df, freq, tz=None): """ set timezone for pandas """ index_name = df.index.name # fix timezone if isinstance(df.index[0], str): # timezone df exists if ("-" in df.index[0][-6:]) | ("+" in df.index[0][-6:]): df.index = pd.to_datetime(df.index, utc=False) ...
add custom data to data store
def record(self, timestamp, *args, **kwargs): """ add custom data to data store """ if self.output_file is None: return data = {'datetime': timestamp} # append all data if len(args) == 1: if isinstance(args[0], dict): data.update(dict(arg...
Downloads historical data from Interactive Brokers
def get_data_ib(instrument, start, resolution="1 min", blotter=None, output_path=None): """ Downloads historical data from Interactive Brokers :Parameters: instrument : mixed IB contract tuple / string (same as that given to strategy) start : str Back...
Converts given DataFrame to a QTPyLib - compatible format and timezone
def prepare_data(instrument, data, output_path=None, index=None, colsmap=None, kind="BAR", resample="1T"): """ Converts given DataFrame to a QTPyLib-compatible format and timezone :Parameters: instrument : mixed IB contract tuple / string (same as that given to strategy...
Store QTPyLib - compatible csv files in Blotter s MySQL. TWS/ GW data are required for determining futures/ options expiration
def store_data(df, blotter=None, kind="BAR"): """ Store QTPyLib-compatible csv files in Blotter's MySQL. TWS/GW data are required for determining futures/options expiration :Parameters: df : dict Tick/Bar data :Optional: blotter : str Store MySQL server used...
be aware of default windows
def _set_windows(self, ticks, bars): """ be aware of default windows """ self.tick_window = ticks self.bar_window = bars
Get bars for this instrument
def get_bars(self, lookback=None, as_dict=False): """ Get bars for this instrument :Parameters: lookback : int Max number of bars to get (None = all available bars) as_dict : bool Return a dict or a pd.DataFrame object :Retruns: ...
Get ticks for this instrument
def get_ticks(self, lookback=None, as_dict=False): """ Get ticks for this instrument :Parameters: lookback : int Max number of ticks to get (None = all available ticks) as_dict : bool Return a dict or a pd.DataFrame object :Retruns: ...
Shortcut to self. get_ticks ( lookback = 1 as_dict = True ) [ last ]
def get_price(self): """ Shortcut to self.get_ticks(lookback=1, as_dict=True)['last'] """ tick = self.get_ticks(lookback=1, as_dict=True) return None if tick is None else tick['last']
Get last quote for this instrument
def get_quote(self): """ Get last quote for this instrument :Retruns: quote : dict The quote for this instruments """ if self in self.parent.quotes.keys(): return self.parent.quotes[self] return None
Get orderbook for the instrument
def get_orderbook(self): """Get orderbook for the instrument :Retruns: orderbook : dict orderbook dict for the instrument """ if self in self.parent.books.keys(): return self.parent.books[self] return { "bid": [0], "bidsize": ...
Shortcut for instrument. order (... ) and accepts all of its optional parameters <#qtpylib. instrument. Instrument. order > _
def market_order(self, direction, quantity, **kwargs): """ Shortcut for ``instrument.order(...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) quan...
Shortcut for instrument. order (... ) and accepts all of its optional parameters <#qtpylib. instrument. Instrument. order > _
def limit_order(self, direction, quantity, price, **kwargs): """ Shortcut for ``instrument.order(...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) ...
Shortcut for instrument. order ( BUY... ) and accepts all of its optional parameters <#qtpylib. instrument. Instrument. order > _
def buy(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ self.parent.order("BUY", self, qua...
Shortcut for instrument. order ( BUY... ) and accepts all of its optional parameters <#qtpylib. instrument. Instrument. order > _
def buy_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ kwargs['limit_price'] = 0 ...
Shortcut for instrument. order ( BUY... ) and accepts all of its optional parameters <#qtpylib. instrument. Instrument. order > _
def buy_limit(self, quantity, price, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity price : float ...
Shortcut for instrument. order ( SELL... ) and accepts all of its optional parameters <#qtpylib. instrument. Instrument. order > _
def sell(self, quantity, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ self.parent.order("SELL", self, ...
Shortcut for instrument. order ( SELL... ) and accepts all of its optional parameters <#qtpylib. instrument. Instrument. order > _
def sell_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ kwargs['limit_price'] = 0...
Shortcut for instrument. order ( SELL... ) and accepts all of its optional parameters <#qtpylib. instrument. Instrument. order > _
def sell_limit(self, quantity, price, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity price : float ...
Get the positions data for the instrument
def get_positions(self, attr=None): """Get the positions data for the instrument :Optional: attr : string Position attribute to get (optional attributes: symbol, position, avgCost, account) :Retruns: positions : dict (positions) / float/s...
Modify quantity and/ or limit price of an active order for the instrument
def modify_order(self, orderId, quantity=None, limit_price=None): """Modify quantity and/or limit price of an active order for the instrument :Parameters: orderId : int the order id to modify :Optional: quantity : int the required quantit...
Modify bracket order
def modify_order_group(self, orderId, entry=None, target=None, stop=None, quantity=None): """Modify bracket order :Parameters: orderId : int the order id to modify :Optional: entry: float new entry limit price (for unfilled limit orders o...
Modify stop order. Auto - discover ** orderId ** and ** quantity ** and invokes self. modify_order (... ).
def move_stoploss(self, stoploss): """Modify stop order. Auto-discover **orderId** and **quantity** and invokes ``self.modify_order(...)``. :Parameters: stoploss : float the new stoploss limit price """ stopOrder = self.get_active_order(order_type="S...
Get margin requirements for intrument ( futures only )
def get_margin_requirement(self): """ Get margin requirements for intrument (futures only) :Retruns: margin : dict margin requirements for instrument (all values are ``None`` for non-futures instruments) """ contract = self.get_contract() ...
Get maximum contracts allowed to trade baed on required margin per contract and current account balance ( futures only )
def get_max_contracts_allowed(self, overnight=True): """ Get maximum contracts allowed to trade baed on required margin per contract and current account balance (futures only) :Parameters: overnight : bool Calculate based on Overnight margin (set to ``False``...
Check if instrument pnl is within given range
def pnl_in_range(self, min_pnl, max_pnl): """ Check if instrument pnl is within given range :Parameters: min_pnl : flaot minimum session pnl (in USD / IB currency) max_pnl : flaot maximum session pnl (in USD / IB currency) :Retruns: ...
Parse a single entry from show interfaces output.
def parse_intf_section(interface): """Parse a single entry from show interfaces output. Different cases: mgmt0 is up admin state is up Ethernet2/1 is up admin state is up, Dedicated Interface Vlan1 is down (Administratively down), line protocol is down, autostate enabled Ethernet154/...
Convert hh: mm: ss to seconds.
def convert_hhmmss(hhmmss): """Convert hh:mm:ss to seconds.""" fields = hhmmss.split(":") if len(fields) != 3: raise ValueError("Received invalid HH:MM:SS data: {}".format(hhmmss)) fields = [int(x) for x in fields] hours, minutes, seconds = fields return (hours * 3600) + (minutes * 60) +...
The show bgp all summary vrf all table can have entries that wrap multiple lines.
def bgp_normalize_table_data(bgp_table): """The 'show bgp all summary vrf all' table can have entries that wrap multiple lines. 2001:db8:4:701::2 4 65535 163664 163693 145 0 0 3w2d 3 2001:db8:e0:dd::1 4 10 327491 327278 145 0 0 3w1d 4 ...
Generator that parses a line of bgp summary table and returns a dict compatible with NAPALM
def bgp_table_parser(bgp_table): """Generator that parses a line of bgp summary table and returns a dict compatible with NAPALM Example line: 10.2.1.14 4 10 472516 472238 361 0 0 3w1d 9 """ bgp_table = bgp_table.strip() for bgp_entry in bgp_table.splitlines(): ...
Parse show bgp all summary vrf output information from NX - OS devices.
def bgp_summary_parser(bgp_summary): """Parse 'show bgp all summary vrf' output information from NX-OS devices.""" bgp_summary_dict = {} # Check for BGP summary information lines that have no data if len(bgp_summary.strip().splitlines()) <= 1: return {} allowed_afi = ["ipv4", "ipv6", "l2vp...
Wrapper for Netmiko s send_command method ( for list of commands.
def _send_command_list(self, commands): """Wrapper for Netmiko's send_command method (for list of commands.""" output = "" for command in commands: output += self.device.send_command( command, strip_prompt=False, strip_command=False ) return output
Extract the uptime string from the given Cisco IOS Device. Return the uptime in seconds as an integer
def parse_uptime(uptime_str): """ Extract the uptime string from the given Cisco IOS Device. Return the uptime in seconds as an integer """ # Initialize to zero (years, weeks, days, hours, minutes) = (0, 0, 0, 0, 0) uptime_str = uptime_str.strip() time_li...
Returns a flag with the state of the SSH connection.
def is_alive(self): """Returns a flag with the state of the SSH connection.""" null = chr(0) try: if self.device is None: return {"is_alive": False} else: # Try sending ASCII null byte to maintain the connection alive self._...
Return a set of facts from the devices.
def get_facts(self): """Return a set of facts from the devices.""" # default values. vendor = "Cisco" uptime = -1 serial_number, fqdn, os_version, hostname, domain_name, model = ("",) * 6 # obtain output from device show_ver = self._send_command("show version") ...
Get interface details.
def get_interfaces(self): """ Get interface details. last_flapped is not implemented Example Output: { u'Vlan1': { 'description': u'', 'is_enabled': True, 'is_up': True, 'last_flapped': -1.0, ...
BGP neighbor information.
def get_bgp_neighbors(self): """BGP neighbor information. Supports VRFs and IPv4 and IPv6 AFIs { "global": { "router_id": "1.1.1.103", "peers": { "10.99.99.2": { "is_enabled": true, "uptime": -1, ...
Get environment facts.
def get_environment(self): """ Get environment facts. power and fan are currently not implemented cpu is using 1-minute average """ environment = {} # sys_resources contains cpu and mem output sys_resources = self._send_command("show system resources") ...
Get interface IP details. Returns a dictionary of dictionaries.
def get_interfaces_ip(self): """ Get interface IP details. Returns a dictionary of dictionaries. Sample output: { "Ethernet2/3": { "ipv4": { "4.4.4.4": { "prefix_length": 16 } }, ...
Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table having the following keys * mac ( string ) * interface ( string ) * vlan ( int ) * active ( boolean ) * static ( boolean ) * moves ( int ) * last_move ( float ) Format1:
def get_mac_address_table(self): """ Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (...