def login(self, l_args): """Connect to Degiro's API.""" # PARSING ARGS default_credentials = self.__default_credentials parser = argparse.ArgumentParser( add_help=False, prog="login", ) parser.add_argument( "-u", "--username", dest="username", type=str, default=default_credentials.username, help="Username in Degiro's account.", ) parser.add_argument( "-p", "--password", dest="password", type=str, default=default_credentials.password, help="Password in Degiro's account.", ) parser.add_argument( "-o", "--otp", dest="otp", type=int, default=None, help="One time password (2FA).", ) parser.add_argument( "-s", "--topt-secret", dest="topt_secret", type=str, default=None, help="TOTP SECRET (2FA).", ) ns_parser = parse_known_args_and_warn(parser, l_args) if ns_parser: credentials = Credentials() credentials.CopyFrom(default_credentials) credentials.username = ns_parser.username credentials.password = ns_parser.password if ns_parser.otp is not None: credentials.one_time_password = ns_parser.otp if ns_parser.topt_secret is not None: credentials.totp_secret_key = ns_parser.topt_secret self.__trading_api = TradingAPI(credentials=credentials) self.__trading_api.connect() self.setup_extra_credentials() print("You are now logged in !")
def credentials(config_dict): int_account = config_dict['int_account'] username = config_dict['username'] password = config_dict['password'] credentials = Credentials( int_account=int_account, username=username, password=password, ) return credentials
def cli(username: str, password: str, int_account: int, log_level: str, log_directory: str = None): """ Retrieves a session_id from Degiro Quotecast API.""" from trading.api import API from trading.pb.trading_pb2 import Credentials credentials = Credentials(int_account=int_account, username=username, password=password) api = API(credentials=credentials) api.connect() click.secho('Connection done !', bg='blue') click.secho(f'Session id : {api.connection_storage.session_id}', bg='blue')
def menu(): """Degiro Menu""" # SETUP CREDENTIALS credentials = Credentials( int_account=None, username=config.DG_USERNAME, password=config.DG_PASSWORD, one_time_password=None, totp_secret_key=config.DG_TOTP_SECRET, ) # SETUP CONTROLLER degiro_controller = DegiroController(credentials=credentials) degiro_controller.help() while True: # Get input command from user if session and gtff.USE_PROMPT_TOOLKIT: completer = NestedCompleter.from_nested_dict( {c: None for c in degiro_controller.CHOICES}) an_input = session.prompt( f"{get_flair()} (pa)>(degiro)> ", completer=completer, ) else: an_input = input(f"{get_flair()} (pa)>(degiro)> ") try: process_input = degiro_controller.switch(an_input) if process_input is not None: return process_input except SystemExit: print("The command selected doesn't exist\n") continue
from trading.pb.trading_pb2 import Credentials # SETUP LOGGING LEVEL logging.basicConfig(level=logging.DEBUG) # SETUP CONFIG DICT with open('config/config.json') as config_file: config_dict = json.load(config_file) # SETUP CREDENTIALS int_account = config_dict['int_account'] username = config_dict['username'] password = config_dict['password'] credentials = Credentials( int_account=int_account, username=username, password=password, ) # SETUP TRADING API trading_api = TradingAPI(credentials=credentials) # CONNECT trading_api.connect() # FETCH DATA - MESSAGE products_config = trading_api.get_products_config(raw=False) # DISPLAY - MESSAGE for item in products_config.values: print(item)
def get_session_id( credentials: Credentials, session: requests.Session = None, logger: logging.Logger = None, ) -> str: """ Establish a connection with Degiro's Trading API. Args: credentials (Credentials): credentials.int_account (int) Account unique identifer in Degiro's system. It is optional. credentials.password (str) Password used to log in the website. It is mandatory. credentials.username (str) Username used to log in the website. It is mandatory. credentials.totp_secret is optional. Secret code for Two-factor Authentication (2FA). It is optional. session (requests.Session, optional): If you one wants to reuse existing "Session" object. Defaults to None. logger (logging.Logger, optional): If you one wants to reuse existing "Logger" object. Defaults to None. Raises: ConnectionError: Connection failed. Returns: str: Session id """ if logger is None: logger = build_logger() if session is None: session = build_session() if credentials.HasField('oneof_2fa') is True: url = urls.LOGIN + '/totp' username = credentials.username password = credentials.password if credentials.HasField('totp_secret_key') is True: totp_secret_key = credentials.totp_secret_key one_time_password = str(otp.get_totp(totp_secret_key)) else: one_time_password = credentials.one_time_password payload_dict = { 'username': username, 'password': password, 'isPassCodeReset': False, 'isRedirectToMobile': False, 'queryParams': {}, 'oneTimePassword': one_time_password, } else: url = urls.LOGIN username = credentials.username password = credentials.password payload_dict = { 'username': username, 'password': password, 'isPassCodeReset': False, 'isRedirectToMobile': False, 'queryParams': {}, } request = requests.Request( method='POST', url=url, json=payload_dict, ) prepped = session.prepare_request(request) response = None try: response = session.send(prepped, verify=False) response_dict = response.json() except Exception as e: logger.fatal('response:%s', response) raise ConnectionError(e) logger.info('get_session_id:response_dict: %s', response_dict) if 'sessionId' in response_dict: return response_dict['sessionId'] elif 'status' in response_dict and response_dict['status'] == 6: logger.fatal('response_dict:%s', response_dict) raise ConnectionError( '2FA is enabled, please provide the "totp_secret".') else: logger.fatal('response_dict:%s', response_dict) raise ConnectionError('No session id returned.')
# SETUP LOGGING LEVEL logging.basicConfig(level=logging.DEBUG) # SETUP CONFIG DICT with open('config/config.json') as config_file: config_dict = json.load(config_file) # SETUP CREDENTIALS username = config_dict['username'] password = config_dict['password'] one_time_password = config_dict['one_time_password'] credentials = Credentials( int_account=None, username=username, password=password, one_time_password=one_time_password, ) # SETUP TRADING API trading_api = TradingAPI(credentials=credentials) # CONNECT trading_api.connect() # ACCESS SESSION_ID session_id = trading_api.connection_storage.session_id print('You are now connected, with the session id :', session_id)
def handle_sigterm(*args): raise KeyboardInterrupt() signal(SIGTERM, handle_sigterm) # logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') logger = logging.getLogger('degiro-preorder') # parameters PREORDERS_FILE = '/app/preorders.json' FINNHUB_TOKEN = os.environ['FINNHUB_TOKEN'] credentials = Credentials( int_account=int(os.environ['DG_INTACCOUNT']), username=os.environ['DG_USERNAME'], password=os.environ['DG_PASSWORD'], ) trading_api_mutex = Lock() trading_api = TradingAPI(credentials=credentials) trading_api.connect() trading_api.get_account_info() logger.info('connected to DEGIRO API.') # set logging levels for libs to critical or higher for key, value in logging.Logger.manager.loggerDict.items(): if key.startswith('trading'): logging.getLogger(key).setLevel(logging.CRITICAL + 1) elif key != 'degiro-preorder': logging.getLogger(key).setLevel(logging.CRITICAL)
# SETUP LOGGING LEVEL logging.basicConfig(level=logging.DEBUG) # SETUP CONFIG DICT with open('config/config.json') as config_file: config_dict = json.load(config_file) # SETUP CREDENTIALS username = config_dict['username'] password = config_dict['password'] totp_secret_key = config_dict['totp_secret_key'] credentials = Credentials( int_account=None, username=username, password=password, totp_secret_key=totp_secret_key, ) # SETUP TRADING API trading_api = TradingAPI(credentials=credentials) # CONNECT trading_api.connect() # ACCESS SESSION_ID session_id = trading_api.connection_storage.session_id print('You are now connected, with the session id :', session_id)