Exemplo n.º 1
0
def main():
    a1 = Account()  #Creates an account with default values
    acc = Account(1122, 20000, 0.045)
    acc.withdraw(2500)
    acc.deposit(3000)
    print(acc.getAccountID(), acc.getBalance(), acc.getMonthlyInterestRate(),
          acc.getMonthlyInterest())
Exemplo n.º 2
0
    def selectAccount(self):

        flag = 0

        with open('accounts.txt') as f:
            lines = f.readlines()

        for line in lines:
            data = line.split(" // ")
            a = Account(str(data[0]), str(data[1]))

            if len(self.accounts) == 0:
                self.accounts.append(a)
                print("Account selected: " + data[0])
                flag = 1
                break
            else:
                flagC = 0
                for account in self.accounts:
                    if a.username == account.username:
                        flagC = 1

                if flagC == 0:
                    self.accounts.append(a)
                    print("Account selected: " + data[0])
                    flag = 1
                    break

        if flag == 1:
            return a
        else:
            return Account("", "")
Exemplo n.º 3
0
def initial_accounts(scenario, outline):
    acc1 = Account('1', 0)
    acc2 = Account('2', 150)
    accounts_dict = {}
    accounts_dict[acc1.id] = acc1
    accounts_dict[acc2.id] = acc2
    world.accounts = accounts_dict
    world.deposit_to = accounts_dict
Exemplo n.º 4
0
def initial_accounts(scenario,outline):
    acc1 = Account('1', 0)
    acc2 = Account('2', 150)
    accounts_dict = {}
    accounts_dict[acc1.id] = acc1
    accounts_dict[acc2.id] = acc2
    world.accounts=accounts_dict
    world.withdrawal_from = accounts_dict
Exemplo n.º 5
0
    def test_init(self):
        with self.assertRaises(TypeError):
            Account('100.0')

        with self.assertRaises(ValueError):
            Account(-100.0)

        account = Account()
        self.assertEqual(account.balance, 0.0)
Exemplo n.º 6
0
 def test_decimals(self):
     # Long with decimals
     a = Account(2)
     a.EnterPosition('Long', 1, 0.00000001)
     self.assertEqual(a.TotalValue(0.00000002), 3)
     a.ClosePosition(a.Positions[0], 1, 0.00000002)
     self.assertEqual(a.BuyingPower, 3)
     #Short with decimals
     a = Account(2)
     a.EnterPosition('Short', 1, 0.00000002)
     self.assertEqual(a.TotalValue(0.00000001), 2.5)
     a.ClosePosition(a.Positions[0], 1, 0.00000001)
     self.assertEqual(a.BuyingPower, 2.5)
Exemplo n.º 7
0
	def load_test_user(self):
		"""
		Test function that auto-generate accounts and appended to the account list.
		"""
		bank = Bank("RBC", 5000)
		bank2 = Bank("RBC", 5000)
		bank3 = Bank("RBC", 5000)
		user1 = User("Saida", 20)
		user2 = User("Andrew", 20)
		user3 = User("Scott", 20)
		self._accounts.append(Account(bank3, user3))
		self._accounts.append(Account(bank2, user2))
		self._accounts.append(Account(bank, user1))
Exemplo n.º 8
0
    def test_isOwner(self):
        #boundary - is owner
        acc = Account(1, 10, 1234)
        owner = acc.getOwner()
        self.assertEqual(owner, '1234')

        #boundary - not owner
        acc = Account(1, 10, 1234)
        swner = acc.getOwner()
        self.assertNotEqual(owner, '12345')

        #boundary - not owner
        acc = Account(1, 10, 1234)
        owner = acc.getOwner()
        self.assertNotEqual(owner, 'abc')
Exemplo n.º 9
0
    def __init__(self, master):
        super().__init__(master)
        self.master = master

        self.user = User()
        self.account = Account()

        self.master.geometry("500x500")
        self.master.title("Most Secure banking")
        self.master.geometry("500x500")
        self.master.config(bg='orange')
        # pages
        self.entry_page = Frame(self.master)
        self.user_create_page = Frame(self.master)
        self.user_logged_page = Frame(self.master)
        self.user_login_page = Frame(self.master)

        self.user_deposit_page = Frame(self.master)
        self.user_withdraw_page = Frame(self.master)
        self.user_edit_page = Frame(self.master)
        self.user_delete_page = Frame(self.master)
        self.user_send_page = Frame(self.master)
        self.user_overview_page = Frame(self.master)

        self.UI_elements()
        self.create_entry_page()
        self.open_windows = []
Exemplo n.º 10
0
    def mosaicClick(self):
        c = NemConnect(self.host.get(), int(self.port.get()))

        privkey = self.privKeyEntry.get()
        fqn = self.create_namespaceNameEntry.get(
        ) + '.' + self.create_mosaicNameEntry.get()
        desc = self.mosaicDescText.get("1.0", END)
        defaultProps = {
            'divisibility': int(self.m_d.get()),
            'initialSupply': int(self.m_is.get()),
            'supplyMutable': True if self.m_ms.get() else False,
            'transferable': True if self.m_t.get() else False
        }
        multisig = self.multisigPubKeyEntry.get() if self.multisigEnabled.get(
        ) else None

        if self.m_hasLevy.get():
            defaultProps['levy'] = {
                "type":
                int(self.m_levy_type.get()),
                "recipient":
                self.m_levy_recipient.get(),
                "mosaicFqn":
                self.m_levy_namespace.get() + '.' + self.m_levy_mosaic.get(),
                "fee":
                int(self.m_levy_fee.get())
            }
        try:
            a = Account(privkey)
            ok, j = c.prepareMosaicCreation(a.getHexPublicKey(), multisig, fqn,
                                            desc, defaultProps)
            self.commonHandle(c, a, ok, j)

        except Exception as e:
            self.report(str(e), traceback.format_exc())
Exemplo n.º 11
0
 def createAccount(self,accountNo,custName,balance):
     self.account=Account()
     self.account.setAccountNo(accountNo)
     self.account.setCustName(custName)
     self.account.setBalance(balance)
     self.accounts.update({accountNo:self.account})
     print "Account has been successfully created for account number",accountNo
Exemplo n.º 12
0
    def build_complete_binary_tree(self, depth):
        # Build the complete binary tree structure
        super().build_complete_binary_tree(depth)

        # Construct Account objects
        accounts_per_shard = 10
        num_shards = (2**(depth + 1) - 1)
        num_accounts = accounts_per_shard * num_shards
        linked_accounts_per_account = 2
        self.accounts = [
            Account(id=x,
                    gas_size=random.randint(1, 20),
                    storage_size=random.randint(1, 100))
            for x in range(num_accounts)
        ]
        for account in self.accounts:
            possible_linked_accounts = self.accounts.copy()
            possible_linked_accounts.remove(account)
            account.linked_accounts = list(
                np.random.choice(possible_linked_accounts,
                                 size=linked_accounts_per_account,
                                 replace=False))
            for linked_account in account.linked_accounts:
                account.linked_accounts_tx_count[
                    linked_account] = random.randint(1, 3)

        # Assign accounts to shards
        accounts_list = self.accounts.copy()
        np.random.shuffle(accounts_list)
        for shard in self.shards:
            shard.load = accounts_list[:accounts_per_shard]
            accounts_list = accounts_list[accounts_per_shard:]
        self.account_shard_map = self.build_account_shard_map()
        self.edge_weights_map = self.calculate_edge_weights()
Exemplo n.º 13
0
def main():
    # Create ten accounts
    accounts = [Account(i, 100) for i in range(10)]

    while True:
        # Prompt the user to enter an id
        ID = eval(input('Enter an account id: '))
        while ID > 9 and ID < 0:
            ID = eval(input('Incorrect id, enter again!: '))

        account = accounts[ID]
        
        print('Main Menu')
        print('1: Check Balance\n2: Withdraw\n3: Deposit\n4: Exit')

        choice = eval(input('Enter a choice: '))

        while choice != 4:
            if choice == 1:
                print('The balance is ', account.getBalance())
            elif choice == 2:
                withdrawAmount = eval(input('Enter an amount to withdraw: '))
                account.withdraw(withdrawAmount)
            elif choice == 3:
                depositAmount = eval(input('Enter an amount to deposit: '))
                account.deposit(depositAmount)
            else:
                break
            print('Main Menu')
            print('1: Check Balance\n2: Withdraw\n3: Deposit\n4: Exit')

            choice = eval(input('Enter a choice: '))
Exemplo n.º 14
0
    def create_account(self, username, password, first_name, last_name,
                       address):
        """
        Creates a bank account for the user
        :param username: username
        :param password: password
        :param first_name: first name
        :param last_name: last name
        :param address: home address
        :return: Tuple that contains boolean variable that determines if account creation is
         successful or not and a message
        """

        # Check if the username does not exist
        if not username in self.account_data:

            next_account_id = len(self.account_data.keys()) + 1
            # If the account doesn't exist, then we can create a bank account with this username
            self.account_data[username] = Account(next_account_id, username,
                                                  password, first_name,
                                                  last_name, address)

            return (True, "Account has been successfully created")

        # Username already exists. User must enter a different username
        return (False,
                "Username already exists. Please enter a different username.")
Exemplo n.º 15
0
def register():
    with sqlite3.connect("data/database.db") as database:
        response = {}
        cursor = database.cursor()
        session.clear()

        if (request.is_json):
            content = request.get_json()
            if ("username" in content and "password" in content
                    and "contact" in content):
                account = Account(name=content["username"],
                                  contact=content["contact"])
                if (register_account(cursor, account, content["password"])):
                    response["status"] = "success"
                else:
                    response["status"] = "error"
                    response["reason"] = "registeration failed"
            else:
                response["status"] = "error"
                response["reason"] = "missing username or password"
        else:
            response["status"] = "error"
            response["reason"] = "Invalid JSON"

        database.commit()
        cursor.close()
        return json.dumps(response)
Exemplo n.º 16
0
 def __init__(self):
     self.user = User()
     self.account = Account()
     self.employee = Employee()
     self.service = Service()
     self.utilities = Utilities()
     self.initAmt = 0
Exemplo n.º 17
0
 def transactionCodeChooser(self, lineData):
     transactionCode = lineData[self.transactionIdx]
     accountTo = lineData[self.accountToIdx]
     accountFrom = lineData[self.accountFromIdx]
     amount = lineData[self.amountDataIdx]
     name = lineData[self.nameDataIdx]
     if self.accountDict.has_key(accountTo):
         if transactionCode == "DL":
             if self.accountDict[accountTo].canDeleteAccount(name):
                 del self.accountDict[accountTo]
             else:
                 print "Incorrect name or account does not exist"
         elif transactionCode == "TR":
             if self.accountDict.has_key(accountFrom):
                 if not self.accountDict[accountTo].transfer(
                         amount, self.accountDict[accountFrom]):
                     print "Error Transferring"
             else:
                 print "Error Transferring"
         elif transactionCode == "WD":
             if not self.accountDict[accountTo].withdrawMoney(amount):
                 print "Withdraw error"
         elif transactionCode == "DE":
             if not self.accountDict[accountTo].depositMoney(amount):
                 print "Deposit error"
     else:
         if transactionCode == "CR":
             wasCreated = Account(accountTo, amount, name,
                                  self.accountDict).isCreated
Exemplo n.º 18
0
def verifySign(line):
    """: ([a-f0-9]+) : ([a-f0-9]+) : ([a-f0-9]+) : ([0-9]{2}) : ([a-f0-9]+)$"""
    f = inspect.currentframe()
    rematch = f.f_back.f_globals[f.f_code.co_name].__doc__
    res = re.match(rematch, line)
    if not res:
        return False

    privateKeyHex = res.group(1)
    expectedPublic = unhexlify(res.group(2))
    expectedSignature = unhexlify(res.group(3))
    dataLength = int(res.group(4))
    data = unhexlify(res.group(5))
    assert (len(data) == dataLength)

    account = Account(privateKeyHex)
    if account.pk == expectedPublic:
        computedSignature = account.sign(data)
        if computedSignature == expectedSignature:
            return True
        else:
            print('Failed when calculating signature:')
            print('  computed signature:' + hexlify(computedSignature))
            print('  expected signature:' + hexlify(expectedSignature))
            return False

    else:
        print('Failed public from private:')
        print('  computed public:' + hexlify(account.pk))
        print('  expected public:' + hexlify(expectedPublic))
        return False
Exemplo n.º 19
0
    def pressedSettings(self, event):
        sender = self.sender()
        id = 0
        for bid, btn in self.buttonsMap.items():
            if btn == sender:
                id = bid

        try:
            current_account_id, current_account_login, current_account_password, current_account_status = \
                self.getRowInformation(id)
        except:
            sender.setStyleSheet("background-color: #FF0000")
            return

        sender.setStyleSheet("background-color: #E1E1E1")

        user = None
        if not id in users:
            user = Account(current_account_id, current_account_login,
                           current_account_password, current_account_status,
                           True, 0, 0, 0, 0)
            users[id] = user
        else:
            user = users[id]
            user.login = current_account_login
            user.password = current_account_password
        self.createSettingsForAccountWindow(user)
Exemplo n.º 20
0
def verifyKey(line):
    """^: ([a-f0-9]+) : ([a-f0-9]+) : ([a-f0-9]+) : ([A-Z2-7]+)$"""
    f = inspect.currentframe()
    rematch = f.f_back.f_globals[f.f_code.co_name].__doc__
    res = re.match(rematch, line)
    if not res:
        return False

    privateKeyHex = res.group(1)
    expectedPublic = unhexlify(res.group(3))
    expectedAddress = res.group(4)

    account = Account(privateKeyHex)
    if account.pk == expectedPublic:
        if account.address == expectedAddress:
            return True
        else:
            print('Failed when calculating address:')
            print('  computed address:' + account.address)
            print('  expected address:' + expectedAddress)
            return False

    else:
        print('Failed public from private:')
        print('  computed public:' + hexlify(accountp.pk))
        print('  expected public:' + hexlify(expectedPublic))
        return False
Exemplo n.º 21
0
    def Start(self, InitialCapital, Logic, Lookback=1, Start=False, End=False):
        # Initialize account
        self.Account = Account(InitialCapital)

        # Adjust custom timeframe
        if not (Start): Start = self.Data['date'].iloc[0]
        if not (End): End = self.Data['date'].iloc[-1]
        self.Start, self.End = Start, End
        self.Timeframe = self.Data.loc[(self.Data['date'] >= Start)
                                       & (self.Data['date'] <= End)]

        # Enter backtest ---------------------------------------------

        for Index, Today in self.Timeframe.iterrows():
            Days = [self.Data.loc[Index]]
            for Day in range(Lookback):
                try:
                    Days.insert(1, self.Data.loc[Index - Day - 1])
                except KeyError:
                    pass

            try:
                Days.insert(1, self.Data.loc[Index + 1])
            except KeyError:
                pass

            # Update account variables
            self.Account.Date = Today['date']
            self.Account.Equity.append(self.Account.TotalValue(Today['open']))

            # Execute trading logic
            Logic(self.Account, Period(Days))

            # Cleanup empty positions
            self.Account.PurgePositions()
Exemplo n.º 22
0
def create_account():
    print("Choice number 1 is selected by the customer\n")

    if len(set_of_accounts) < 10:
        name = str(input("Input Fullname : "))
        pin = str(input("Please input a pin of your choice : "))
        balance = eval(
            input("Please input a amount to deposit to start an account : "))

        account = Account(name, pin, balance)
        set_of_accounts.add(account)

        print("\n----New account created successfully !----")
        print("Note! Please remember the Name and Pin")
        print("========================================")

    else:
        print(
            "\nCustomer registration exceed reached the no:of spaces left are: "
            + str((len(set_of_accounts)) - 10))

    # This statement below helps the user to go back to the start of the program (main menu).
    input(
        "Please press enter key to go back to main menu to perform another function or exit ..."
    )
Exemplo n.º 23
0
def create_account():
    print("Choice number 1 is selected by the customer\n")

    # creates new accounts with the attributes limit to 9 accounts to keep project small
    if len(set_of_accounts) < 10:
        nric = check_NRIC_not_repeated()
        name = str(input("Input Fullname : "))
        pin = str(input("Please input a pin of your choice : "))
        balance = check_balance_valid(
            "Please input a amount to deposit to start an account: ")

        #create Account object and add the set_of_accounts
        account = Account(nric, name, pin, balance)
        set_of_accounts.add(account)

        print("\n----New account created successfully !----")
        print("Note! Please remember the Name and Pin")
        print("========================================")

    else:
        print(
            "\nCustomer registration exceed reached the no:of spaces left are: "
            + str((len(set_of_accounts)) - 10))

    # This statement below helps the user to go back to the start of the program (main menu).
    input(
        "Please press enter key to go back to main menu to perform another function or exit ..."
    )
Exemplo n.º 24
0
def opt_wrapper(params):
    """
        optimizing for periods
    """
    # assign parameters
    periods_bol = int(params[0])  # space from optimizer returns floats
    periods_adx = int(params[1])
    periods_rsi = int(params[2])
    adx_value = int(params[3])

    ###### Define Simulations ######
    data = Data(start_date="20-03-01")  # historical data interfal: hours
    df = data.load()
    strategy = Strategy(df=df,
                        periods_bol=periods_bol,
                        periods_adx=periods_adx,
                        periods_rsi=periods_rsi,
                        adx_value=adx_value)

    account = Account(balance={"euro": 1000, "btc": 0}, av_balance=0.8)

    sim = Sim(strategy=strategy,
              account=account,
              stake_amount=50,
              stop_loss=0.02)
    sim_result = sim.start()

    # negate as optimization looks for a minimum
    sim_result = -sim_result["account"].balance["euro"]

    return sim_result
Exemplo n.º 25
0
    def showMenu(self):
        print("************Welcome to Account Bank**************")

        action = self.getUserOption()

        if action == 1:
            print(self.currentAccount.showBalance())
            self.loading('self.loading')
            self.showMenu()
        elif action == 2:
            value = self.tryParseInt("How much do you want to withdraw? ")
            self.currentAccount.withdrown(value)
            self.loading('withdrawing')
            self.showMenu()
        elif action == 3:
            value = self.tryParseInt("How much do you want to deposit? ")
            self.currentAccount.deposit(value)
            self.loading('depositing')
            self.showMenu()
        elif action == 4:
            newAccountID = input(
                "Type the accountID do you want to transfer to?")
            newAccount = Account(newAccountID)
            value = self.tryParseInt("How much do you want to transfer? ")
            self.currentAccount.transfer(newAccount, value)
            self.loading('transfering')
            self.showMenu()
        elif action == 5:
            self.loading('exiting')
            sys.exit()
        else:
            self.showMenu()
Exemplo n.º 26
0
    def transferClick(self):
        try:
            c = NemConnect(self.host.get(), int(self.port.get()))

            privkey = self.privKeyEntry.get()
            multisig = self.multisigPubKeyEntry.get(
            ) if self.multisigEnabled.get() else None
            recipient = self.transferRecipient.get()
            amount = int(self.transferAmount.get())
            message = self.transferMessage.get("1.0", END)
            mosaics = map(
                lambda x:
                (x['t'].get() + '.' + x['m'].get(), int(x['q'].get())),
                self.attachments)

            if len(self.attachments) > 0:
                amount *= 1000000

            a = Account(privkey)
            ok, j = c.prepareTransfer(a.getHexPublicKey(), multisig, recipient,
                                      amount, message, mosaics)
            self.commonHandle(c, a, ok, j)

        except Exception as e:
            self.report(str(e), traceback.format_exc())
Exemplo n.º 27
0
def run():
    logging.basicConfig(filename='log.txt',
                        filemode='a',
                        format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                        datefmt='%d-%b-%y %H:%M:%S',
                        level=logging.DEBUG)
    logging.info('Initiating Run')
    auth_client = Account()
    history = History('BTC-USD')
    sma50 = history.sma(50)
    sma100 = history.sma(100)
    if sma50 > sma100:
        bull_flag = True
    else:
        bull_flag = False
    while True:
        if datetime.now().minute == 0:
            history = History('BTC-USD')
            if bull_flag is False and history.sma(50) > history.sma(100):
                buy = auth_client.buy('BTC-USD')
                logging.info(f'Golden Cross: {buy}')
                bull_flag = True
            if bull_flag is True and history.sma(50) < history.sma(100):
                sell = auth_client.sell('BTC-USD')
                logging.info(f'Death Cross: {sell}')
                bull_flag = False
            else:
                logging.info('No Crossover event')
            time.sleep((60 * 60) - datetime.now().minute * 60 - (datetime.now().microsecond / 1000000))
        else:
            time.sleep((60 * 60) - datetime.now().minute * 60 - (datetime.now().microsecond / 1000000))
Exemplo n.º 28
0
 def go_to_option(self,option):
     if option==1:
         Account().display_closed_accounts_history()
     if option==2:
         print("Successfully logged out")
     else:
         self.show_menu()
Exemplo n.º 29
0
 def __init__(self, btcTrader, apiName, authId, authPass):
     Engine.__init__(self, apiName, btcTrader, 1) # refresh rate of 1 second. In the futur with the websockets we will probably put 0 and use some kind of select
     self.req = self.CreateRequester(authId, authPass)
     self.depth = {}
     self.clock = Clock()
     self.first = 1
     self.account = Account()
Exemplo n.º 30
0
def load():
    if os.path.isfile('data/accounts.csv'):
        path = 'data/accounts.csv'
    else:
        path = 'data/FakeNameSet20.csv'
    with open(path, mode='r') as csv_file:
        csv_reader = csv.reader(csv_file)
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            else:
                accounts.append(
                    Account(row[0], row[1], row[2], row[3], row[4], row[5],
                            row[6], row[7], row[8], row[9], row[10]))
                line_count += 1
        csv_file.close()

    if os.path.isfile('data/books.json'):
        path = 'data/books.json'
    else:
        path = 'data/booksset1.json'

    js_books = json.load(open(path, 'r'))
    for js_book in js_books:
        book = Book(js_book['author'], js_book['country'],
                    js_book['image_link'], js_book['language'],
                    js_book['link'], js_book['pages'], js_book['title'],
                    js_book['year'])
        books.append(book)