Beispiel #1
0
 def createAccount(self,name,accountType,initialBalance=0):
   try:
     accountType=Account.TYPE_ID[accountType]
   except:
     raise AccountError("%s is not a valid account type" % (accountType,))
   accountData={"name":name,"type_id":accountType,"initial_balance":initialBalance}
   account=Account(self.auth,self.cache,accountData)
   account.onCommit="create"
   account.commit()
   return account
 def test_show_account_with_a_invalid_account(self): 
     client = Client.get_client('mustafa') # from the lion-king
     try:
         Account.show_account(client)
     except SoftLayer.SoftLayerAPIError as slAPIe:
         pass
     except BaseException as be:
         self.assertEquals(be.message, "bad client")
     else:
         self.fail("expected a SoftLayer.SoftLayerAPIError")
    def post(self):
        result = Account.validating_input(self)
        username = self.request.get("username")
        password = self.request.get("password")
        email = self.request.get("email")

        if result == True:
            Account.complete_registration(self, username, password, email)
        else:
            Account.display_error(self, result, username, email)
    def create_account(email, plain_text_password):
        session = DbSessionFactory.create_session()

        account = Account()
        account.email = email
        account.password_hash = AccountService.hash_text(plain_text_password)

        session.add(account)
        session.commit()

        return account
    def get(self, url):
        entry = db.GqlQuery(
            "select * from Entry where subject='%s' order by created desc " % url).get()
    
        if entry:
            
            self.render("permalink.html", entry=entry, url=url,
                        username=Account.valid_cookie(self))

        else:
            if Account.valid_cookie(self):
                self.redirect("/_edit" + url)
            else:
                self.redirect("/login")
    def get(self, url):
        entry = db.GqlQuery(
            "select * from Entry where subject='%s' order by created desc" % url).get()

        if Account.valid_cookie(self):

            if entry:
                self.render("edit.html", content=entry.content,
                            username=Account.valid_cookie(self))
            else:
                self.render("edit.html", content="",
                            username=Account.valid_cookie(self))
        else:
            self.redirect("/login")
    def get(self, post_id):

        entry = Entry.get_by_id(int(post_id))

        if entry:
            if Account.valid_cookie(self):

                self.render("edit.html", content=entry.content,
                            username=Account.valid_cookie(self))

            else:
                self.redirect("login")
        else:
            self.write("error: requested Archive does not exist")
    def test_get_account_with_client(self):
        details = Account.get_details(self.client)
        expectedDict = {'lastName': 'john doe', 
                        'city': 'Reston',
                        'postalCode': '20194', 
                        'modifyDate': '', 
                        'lateFeeProtectionFlag': '', 
                        'firstName': 'john doe', 
                        'companyName': 'company name', 
                        'address1': '1 Main Street', 
                        'accountManagedResourcesFlag': False, 
                        'accountStatusId': 1001, 
                        'statusDate': '', 
                        'brandId': 2, 
                        'email': '*****@*****.**', 
                        'state': 'VA', 
                        'allowedPptpVpnQuantity': 1, 
                        'country': 'US', 
                        'id': 000001, 
                        'officePhone': '7035550001', 
                        'isReseller': 0, 
                        'createDate': '2014-10-02T18:39:47-06:00', 
                        'claimedTaxExemptTxFlag': False}

        self.assertDictEqual(details, expectedDict)
    def get(self):
        username = Account.valid_cookie(self)

        if username:
            self.redirect("/")
        else:
            self.write_form()
    def getAll(self):
        if id == '':
            #TODO better to Raise
            self._errorMessage = 'Required Field Missing: id'
            return False

        res = self._es.es.search(index='names', doc_type='address')
        #TODO check result
        results = res['hits']['hits']
        for account in results:
            print(account['_id'])
            add = Account()
            add.getByID(account['_id'])
            self._accounts.append(add)
            print(len(self._accounts))
        return True
    def get(self, url):
        entries = db.GqlQuery(
            "select * from Entry where subject='%s' order by created desc" % url)

        previous_entries = list(entries)

        self.render("history.html", username=Account.valid_cookie(
            self), url=url, previous_entries=previous_entries)
    def get(self, post_id):

        entry = Entry.get_by_id(int(post_id))

        if entry:
            self.render("archive.html", username=Account.valid_cookie(
                self), entry=entry, url="/archive/" + post_id, subject=entry.subject)
        else:
            self.write("error")
 def testDeposit(self):
     print("---Testing account's deposit method---")
     test_account = Account(200)
     test_account.deposit(211)
     self.assertEqual(411, test_account.amount)
     self.assertEqual(True, test_account.deposit(21.4))
     self.assertEqual(False, test_account.deposit(-42))
     print("\n")
Beispiel #14
0
    def test_AnalogAccountTotalvolume(self):
        '''验证模拟账号最大持仓为3手'''
        userData['headers'] = dict(
            userData['headers'],
            **{'Authorization': userData['Bearer'] + self.token})

        # 获取模拟账户的accountindex
        self.tradeAccountIndex = Account.getSpecialAccountIndex(
            headers=userData['headers'], brokerID=3, accountType=0)

        #模拟账号切换账户
        Account.switchAccount(
            userData['hostName'] + userDataAccount['switchAccount'],
            userData['headers'], self.tradeAccountIndex[0])

        # 获取模拟账号交易token
        traderTokenRes = Trade.getToken(
            userData['hostName'] + userDataAccount["getToken_url"],
            userData['headers'])
        self.assertEqual(traderTokenRes.status_code,
                         userData['status_code_200'])
        tradeToken = str(json.loads(
            traderTokenRes.content)["data"]["Token"]).replace("=", "@")

        # 模拟账号开仓
        openParam = {
            userDataWebSocket['orderParam_code']:
            userDataWebSocket['ws_code_210'],
            userDataWebSocket['orderParam_symbol']:
            userDataWebSocket['broker_EURCAD'],
            userDataWebSocket['orderParam_volume']:
            3100
        }
        openPositionRes = TradeOnline.OnlineTradeEvent.tradeEvent(
            self, userDataWebSocket['ws_host'], userDataWebSocket['ws_port'],
            {'token': "" + tradeToken}, openParam)
        self.assertEqual(openPositionRes["code"], 19)
        print("模拟账号最大持仓为3手!")
    def get(self):

        username = Account.valid_cookie(self)

        entries = top_entries()

        if memcache.get("time"):
            age = int(time.time() - memcache.get("time"))
        else:
            age = None
        #entries=db.GqlQuery("select * from Entry order by created desc limit 50")

        self.render("comments.html", username=username,
                    entries=entries, error="", age=age)
def main(argv):
    with open('manifest.json', 'r') as settings_file:
        settings = json.load(settings_file)
    accounts = []

    # Example usage
    for path in settings['accounts']:
        path = Path(path)

        # Create an account with a name and a path
        account = Account.Account(path, name=path.parent.name)

        # Save the account as a CSV
        account.save_csv(path / 'all_transactions.csv')

        # Save the account in an array so that we can merge it at the end
        accounts.append(account)

    # Merge all the accounts into one CSV output file
    Account.merge_accounts(accounts, settings['merged_output'])

    # Merge all the accounts into one CSV output file with a unique date
    Account.merge_accounts(accounts, settings['merged_output_ud'], unique_date=True)
    def get(self):
        entry = db.GqlQuery(
            "select * from Entry where subject='/' order by created desc").get()

        if entry:
            front_content = entry.content
        else:

            front_content = "<h1>Welcome to the Final!!!</h1>"
            entry = Entry(subject="/", content=front_content)
            entry.put()

        self.render("front.html", username=Account.valid_cookie(
            self), front_content=front_content, url="/")
Beispiel #18
0
 def test_1_getBrokers_FM(self):
     brokers = Account.getBrokers(webAPIData['hostName'] +
                                  accountData['getBrokers_url'],
                                  printLogs=0)
     self.assertEqual(brokers.status_code, webAPIData['status_code_200'])
     '''获取FM的经纪商列表'''
     brokerList = []
     #遍历返回来的json的brokers数据
     for item in json.loads(brokers.text)["data"]["brokers"]:
         brokerList.append(item["Broker"])
     brokerList.sort()
     brokerbrokertable = ['KVB', 'FXCM']
     brokerbrokertable.sort()
     self.assertListEqual(brokerList, brokerbrokertable)
Beispiel #19
0
def resetPassword():
    if request.method == "GET":
        token = request.args.get('token')
        userId = Account.checkToken(token)
        if userId == 0:
            return "Invalid URL"
        elif userId == -1:
            return "Reset token expired: please try again"
        else:
            return render_template("password/reset.html")

    if request.method == "POST":
        token = request.json["token"]
        userId = Account.checkToken(token)
        if userId == 0:
            return "Invalid URL"
        elif userId == -1:
            return "Reset token expired: please try again"
        else:
            newPassword = request.json["newPassword"]
            if len(newPassword) < 8:
                return "Password must be at least 8 characters"
            return Account.resetPassword(userId, newPassword)
Beispiel #20
0
    def setUp(self):
        #交易员登陆---------------------
        tradeDatas = {"account":webAPIData['account'], "password":webAPIData['passwd'], "remember":"false"}
        tradeSignin = Auth.signin(webAPIData['hostName'] + authData['signin_url'], webAPIData['headers'], tradeDatas)
        #登录成功,返回200 ok
        self.assertEqual(tradeSignin.status_code, webAPIData['status_code_200'])
        #保存账号的nickName,待获取userID使用
        self.tradeNickName = json.loads(tradeSignin.text)['data']['nickname']
        # #保存登录时的token,待登出使用
        self.tradeUserToken = json.loads(tradeSignin.text)['data']['token']
        #保存userID
        self.tradeUserID = json.loads(tradeSignin.text)['data']['id']
        #规整headers
        self.tradeHeaders = dict(webAPIData['headers'], **{webAPIData['Authorization'] : webAPIData['Bearer'] + self.tradeUserToken})
        #获取指定经纪商的accountIndex。当前为:pcio
        self.tradePicoAccountIndex = Account.getSpecialAccountIndex(headers = self.tradeHeaders, brokerID=riskControlData["testBrokerID"])[0]
        self.switchTradeAccount = Account.switchAccount(webAPIData['hostName'] + accountData['switchAccount'], self.tradeHeaders, index=self.tradePicoAccountIndex)
        #账号切换成功
        self.assertEqual(self.switchTradeAccount.status_code, webAPIData['status_code_200'])
        #获取交易员交易token
        self.tradeToken = Account.getToken(self.tradeHeaders, onlyTokn="true", printLogs=1)
        
        #跟随者登陆---------------------
        followDatas = {"account":webAPIData['followAccount'], "password":webAPIData['followPasswd'], "remember":"false"}
        followSignin = Auth.signin(webAPIData['hostName'] + authData['signin_url'], webAPIData['headers'], followDatas)
        #登录成功,返回200 ok
        self.assertEqual(followSignin.status_code, webAPIData['status_code_200'])
        # #保存登录时的token,待登出使用
        self.followUserToken = json.loads(followSignin.text)['data']['token']
        #规整headers
        self.followHeaders = dict(webAPIData['headers'], **{webAPIData['Authorization'] : webAPIData['Bearer'] + self.followUserToken})
        #获取指定经纪商的accountIndex。当前为:pcio
        self.followPicoAccountIndex = Account.getSpecialAccountIndex(headers = self.followHeaders, brokerID=riskControlData["testBrokerID"])[0]
        self.switchFollowAccount = Account.switchAccount(webAPIData['hostName'] + accountData['switchAccount'], self.followHeaders, index=self.followPicoAccountIndex)
        #账号切换成功
        self.assertEqual(self.switchFollowAccount.status_code, webAPIData['status_code_200'])
        #获取跟随者交易token
        self.followToken = Account.getToken(self.followHeaders, onlyTokn="true", printLogs=1)

        #一倍建立跟随
        self.tradeIndex = str(self.tradeUserID) + '_' + self.tradePicoAccountIndex
        #设置跟随策略
        followDatas = {"accountIndex": self.followPicoAccountIndex, webAPIData['followStrategy']: webAPIData['follow_ratio'], 
        webAPIData['follow_setting']: 1, webAPIData['followDirection']: webAPIData['follow_positive']}
        createFollow = FollowManage.createFollow(webAPIData['hostName'] + followData['createFollow_url'] + self.tradeIndex, headers = self.followHeaders, datas =followDatas, interfaceName="createFollow")
        #断言跟随成功
        self.assertEqual(createFollow.status_code, webAPIData['status_code_200'])

        #设置全局风控参数。关闭风控信号
        globalRiskControlData = {webAPIData['signalSwitch']: webAPIData['signalSwitch_close']}
        setRiskControl = RiskControl.setRiskControl(webAPIData['hostName'] + riskControlData['setRiskControl_url'], accountIndex=self.followPicoAccountIndex, headers = self.followHeaders, datas=globalRiskControlData)
        self.assertEqual(setRiskControl.status_code, webAPIData['status_code_200'])

        #设置针对单个交易员的风控参数。初始为默认值
        specialTradeDatas = { "accountIndex": self.followPicoAccountIndex}
        setRiskControlForTrader = RiskControl.setRiskControlForTrader(webAPIData['hostName'] + riskControlData['setRiskControlForTrader_url'] + self.tradeIndex, headers=self.followHeaders, datas=specialTradeDatas, interfaceName="setRiskControlForTrader")
        self.assertEqual(setRiskControlForTrader.status_code, webAPIData['status_code_200'])
Beispiel #21
0
def addPurchase(tripID):
    requiredParams = [
        "purchaserAccountID", "purchaserAccountPassword", "purchaseAmount"
    ]
    if not utils.hasExpectedParams(requiredParams, request):
        tripSquadAPI.logger.error(
            "addPurchase -- Required params not found in request")
        abort(400)

    allParams = requiredParams + ["description"]
    [
        purchaserAccountID, purchaserAccountPassword, purchaseAmountStr,
        purchaseDescription
    ] = utils.parseParams(allParams, request)
    purchaseAmount = 0
    try:
        purchaseAmount = int(purchaseAmountStr)
    except ValueError:
        tripSquadAPI.logger.error(
            "addPurchase -- %s purchaseAmount not valid" % purchaseAmountStr)
        abort(400)

    if not Account.validateAccount(purchaserAccountID,
                                   purchaserAccountPassword):
        tripSquadAPI.logger.error("addPurchase -- %s User not validated" %
                                  purchaserAccountID)
        abort(400)

    trip = Trip.getTripByID(tripID)
    if not trip:
        tripSquadAPI.logger.error("addPurchase -- %s trip not valid" % tripID)
        abort(400)

    if not trip.includesAccount(purchaserAccountID):
        tripSquadAPI.logger.error("addPurchase -- %s ID not valid" %
                                  purchaserAccountID)
        abort(400)

    tripMemberID = TripMember.getTripMemberID(purchaserAccountID, tripID)
    newPurchase = Purchase.createPurchase(tripMemberID,
                                          purchaseAmount,
                                          description=purchaseDescription)

    if not newPurchase:
        tripSquadAPI.logger.error("addPurchase -- failure in db insertion")
        abort(500)

    response = {"purchaseID": newPurchase.ID}
    return json.jsonify(response)
Beispiel #22
0
    def create_account(self, account_number: str, balance: float) -> None:
        """
        Creates an Account and adds it to the PyBank's list of active accounts.

        :param account_number: String value to denote account number.
        :param balance: String float representing the initial account balance.
        :return: None
        """
        if check_amount_validity(balance):
            if not self.get_account(account_number):
                self._accounts.append(
                    Account.Account(account_number, float(balance)))
            else:
                print(
                    "Error, account with this number already exists, please try again!"
                )
Beispiel #23
0
 def __init__(self):
     #Create 10 default accounts when initalized
     for i in range(0, 9):
         #Create account demo account object
         account = Account(100 + i, "Demo Account #" + str(i))
         #initalze default interest
         account.setAnnualIntrRate(0.1)
         #initialize default amount
         account.deposit(100)
         #add account to account list
         self._accountList.append(account)
    def post(self):
        username = Account.valid_cookie(self)
        content = self.request.get("content")

        if content:
            entry = Entry(content=content, username=username)
            entry.put()
            time.sleep(0.1)
            top_entries(True)
            memcache.set("time", time.time())
            self.redirect("/comments")
        else:
            error = "Please enter your comment "
            entries = top_entries()

            self.render("comments.html", username=username,
                        entries=entries, error=error)
Beispiel #25
0
    def getAccountTitle(self, alias):
        simplified = Account.simplifyAlias(alias)
              
        # if the alias when simplified is exactly a key to the map
        # then return the title of the account        
        if simplified in self.map_alias_to_title.keys():
            #print "matches exactly", simplified
            return self.map_alias_to_title[simplified]

        # check to see if key appears at the beginning of simplified
        for key in self.map_alias_to_title.keys():                
            if simplified.find(key) == 0:
                #print "The key,", key, "matches at the beginning of", simplified
                return self.map_alias_to_title[key]
                
        # check to see if key appears somewhere in simplified
        for key in self.map_alias_to_title.keys():                
            if simplified.find(key) > 0:
                #print "The key,", key, "matches somewhere the simplified alias", simplified
                return self.map_alias_to_title[key]
        
        #print "The simplified alias does not match any key:", simplified
        return "UNKNOWN_ACCOUNT"

        # if the alias when simplified is a key to the map
        # then return title        
        if simplified in self.map_alias_to_title.keys():
            return self.map_alias_to_title[simplified]

        # if a key to the map is a leading substring of the alias when simplified 
        # then return title        
        else:
            found = None
            for key in self.map_alias_to_title.keys():
                len_key = len(key)
                if simplified[0:len_key] == key:
                    found = key
                    break
                
        if found == None:
            return "UNKNOWN_ACCOUNT"
        else:
            return self.map_alias_to_title[found]

                           
Beispiel #26
0
    def test_balance(self):
        account = Account(address="b50c2404e699fd985f71b2c3f032059f13d6543b")
        print("set active chain to TestNet")
        chain.set_active_chain(chain.TestNet)
        balance = account.get_balance()
        print("balance", balance)
        assert balance > 0

        nonce = account.get_nonce()
        print("nonce", nonce)
        assert nonce >= 3

        account2 = Account(address="b50c2404e699fd985f71b2c3f032059f13d65432")
        balance = account2.get_balance()
        print("balance", balance)
        assert balance == 0

        account3 = Account.from_keystore("zxcvbnm,", path_join("crypto", "zilliqa_keystore.json"))
        balance = account3.get_balance()
        print("balance", balance)
        assert balance > 0
Beispiel #27
0
def login():

    if request.method == "GET":
        return render_template("login.html")

    if request.method == "POST":
        user = request.get_json()
        username = user["email"]
        password = user["password"]
    if username is not None and password is not None:
        user_id = Login.loginUser(username, password)
        if (isinstance(user_id, int)):
            session["user_id"] = user_id
            session["name"] = Account.getFirstName(user_id)
            return "Success"
        else:
            return user_id  #user_id is a dict with errors if there are errors

    return "Invalid username or password"
Beispiel #28
0
def load_accounts():
    account_name:str;
    password:str;
    interests = [];
    fin = open('accs.txt', mode = 'r');
    line = fin.readline();
    while line != '':
        if line == '':
            return;
        account_name = line.rstrip('\n');
        line = fin.readline();
        password = line.rstrip('\n');
        line = fin.readline().rstrip('\n');
        interests = line.split(sep = ' ');
        #interests = tuple(interests);
        accounts[account_name] = \
            Account.Account(account_name, password, interests);
        line = fin.readline();
    fin.close();
Beispiel #29
0
    def test_new_account(self):
        with pytest.raises(ValueError):
            Account()

        account = Account.generate()
        assert account and account.address
        assert account.zil_key.address == account.address

        address = "b50c2404e699fd985f71b2c3f032059f13d6543b"
        account = Account(address=address)
        assert account and account.address
        assert account.checksum_address == zilkey.to_checksum_address(address)
        assert account.zil_key is None

        pub_key = "0x03949D29723DA4B2628224D3EC8E74C518ACA98C6630B00527F86B8349E982CB57"
        private_key = "05C3CF3387F31202CD0798B7AA882327A1BD365331F90954A58C18F61BD08FFC"
        address = "95B27EC211F86748DD985E1424B4058E94AA5814"

        account = Account(address=address, private_key=private_key)
        assert account and account.address
        assert account.checksum_address == zilkey.to_checksum_address(address)
        assert account.zil_key is not None

        account = Account(address=address, public_key=pub_key)
        assert account and account.address
        assert account.checksum_address == zilkey.to_checksum_address(address)
        assert account.zil_key is not None

        account = Account(address=address, public_key=pub_key, private_key=private_key)
        assert account and account.address
        assert account.checksum_address == zilkey.to_checksum_address(address)
        assert account.zil_key is not None

        addr = "1d19918a737306218b5cbb3241fcdcbd998c3a72"
        bech32_addr = "zil1r5verznnwvrzrz6uhveyrlxuhkvccwnju4aehf"
        account1 = Account(address=addr)
        account2 = Account(address=bech32_addr)
        assert account1 == account2
        assert account1.bech32_address == bech32_addr
        assert account2.address == addr
Beispiel #30
0
def registerUser(user, requires_verification=True):
    connection = Database.pool.get_connection()

    response = validate(user)
    if len(response) > 0:
        connection.close()
        return response

    name = user["email"]
    firstName = user["firstName"]
    lastName = user["lastName"]
    institution = user["institution"]
    password = user["password"]
    iAgree = user["iAgree"]

    verifycode = binascii.b2a_hex(os.urandom(15)).decode("utf-8")
    user_data = (name, bcrypt.hashpw(password.encode("utf-8"),
                                     bcrypt.gensalt()), 0, int(time.time()),
                 verifycode, "False", firstName, lastName, institution,
                 defaultJobLimit)

    if requires_verification == False:
        user_data = (name,
                     bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()),
                     0, int(time.time()), verifycode, "True", firstName,
                     lastName, institution, defaultJobLimit)

    with connection.cursor() as cursor:
        cursor.execute(add_user_query, user_data)

    user_id = Account.getUserId(name)

    if requires_verification:
        verifylink = request.url_root + "verify?id={userId}&verify={verifycode}".format(
            userId=user_id, verifycode=verifycode)
        EmailScript.SendEmail(
            "-t 0 -n {username} -u {verifylink} -d {email}".format(
                username=firstName, verifylink=verifylink,
                email=name).split(" "))

    connection.close()
    return "Success"
Beispiel #31
0
def validate(user):
	errors = {}

	if "firstName" not in user:
		errors["firstName"] = "Empty field"
	if "lastName" not in user:
		errors["lastName"] = "Empty field"
	if "institution" not in user:
		errors["institution"] = "Empty field"
	if "email" not in user:
		errors[""] = "Empty field"
	else:
		if "@" not in user["email"]:
			errors["email"] = "Invalid email"
		elif Account.getUserId(user["email"]):
			errors["email"] = "Email is already registered"
	if "password" not in user or len(user["password"]) < 8:
		errors["password"] = "******"

	return errors
Beispiel #32
0
    def process_master_account(self, fileName):
        """Function to create a dictionary of account objects from the master accounts file.
        This allows for a cached version of the master accounts file for any future transactions.
        """
        with open(fileName) as file:
            for line in file:
                #Remove leading and trailing spaces.
                line = line.strip()

                try:
                    #Split line into list, use items in master account line to create Account object.
                    #Store Account objects in dictionary using account number for easy access.
                    items = line.split(" ")
                    accountObj = Account.Account(int(items[0]), int(items[1]),
                                                 items[2])
                    TxnProcess.accounts_dic[
                        accountObj.get_account_num()] = accountObj
                except ValueError:
                    err.process_error("ERR_MASTERACCOUNT")
                    sys.exit()
Beispiel #33
0
class Test(unittest.TestCase):
    acc = Account.MyClass('100', '*****@*****.**')
    accdao = AccountDaoImpl.MyClass()

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testName(self):
        pass

    def testAddAcc(self):
        self.assertEqual(self.accdao.addAcc(self.acc), True)

    def testgetAcc(self):
        self.assertIsNotNone(self.accdao.getAccById("100"), True)

    def testDelAcc(self):
        self.assertEqual(self.accdao.delAccById("100"), True)
Beispiel #34
0
def createAccount():
    requiredParams = ["name", "emailAddress", "password"]
    if not utils.hasExpectedParams(requiredParams, request):
        tripSquadAPI.logger.error(
            "createAccount -- Required params not found in request")
        abort(400)

    [accountName, accountEmail,
     accountPassword] = utils.parseParams(requiredParams, request)
    newAccount = Account.createAccount(accountName, accountEmail,
                                       accountPassword)

    if not newAccount:
        tripSquadAPI.logger.error("createAccount -- failure in db insertion")
        abort(500)

    tripSquadAPI.logger.info(
        "createAccount -- new Account: ID: %s, name: %s, email: %s" %
        (newAccount.ID, newAccount.name, newAccount.email))
    response = {"accountID": newAccount.ID}
    return json.jsonify(response)
Beispiel #35
0
 def test_3_getBrokers_available(self):
     '''获取有效的经纪商列表'''
     params = {"category ": "available"}
     brokers = Account.getBrokers(webAPIData['hostName'] +
                                  accountData['getBrokers_url'],
                                  params="category=available",
                                  printLogs=0)
     self.assertEqual(brokers.status_code, webAPIData['status_code_200'])
     brokerList = []
     for item in json.loads(brokers.text)["data"]["brokers"]:
         brokerList.append(item["Broker"])
     print(brokerList)
     brokerList.sort()
     brokertable = [
         'ADS-SAM', 'Alpari-SAM', 'Ava-SAM', 'Axi-SAM', 'EasyForex-SAM',
         'ExnessCY-SAM', 'FOREX-SAM', 'FXCM', 'FxPro-SAM', 'GKFX-SAM',
         'GoMarkets-SAM', 'ICMarkets-SAM', 'IFMTrade-SAM', 'KVB',
         'Pepperstone-SAM', 'STA-SAM', 'ThinkForexAU-SAM', 'AETOS-SAM'
     ]
     brokertable.sort()
     self.assertListEqual(brokerList, brokertable)
Beispiel #36
0
    def test_getUserAccountSummaryReportOfAccountMobile_002(self):
        datas = {
            'AccountMobile': userData['account'],
            'pageIndex': userData['getUserAccountSummaryReportPageIndex'],
            'pageSize': userData['getUserAccountSummaryReportPageSize'],
            'orderBy': userData['getUserAccountSummaryReport_Orderby']
        }
        url = userData['hostNameOA'] + userDataAccountUrl[
            'getUserAccountSummaryReport_url']

        userAccSummaryRepRes = Account.getUserAccountSummaryReport(
            url, self.headerOA, datas, printLogs=0)
        if userAccSummaryRepRes:
            self.assertEqual(userAccSummaryRepRes.status_code,
                             userData['status_code_200'], '获取账户总览失败!')

            userAccSummaryRepList = json.loads(
                userAccSummaryRepRes.text)['Items']
            if len(userAccSummaryRepList):
                for i in range(len(userAccSummaryRepList)):
                    self.assertEqual(userAccSummaryRepList[i]['AccountMobile'],
                                     '180****8805', '筛选账户总览中手机号的数据错误!')
Beispiel #37
0
def GetAccountBySiteName(siteName, userId) -> Account.Account:
    db = ConnectDatabase()
    cr = db.cursor()
    acc = Account.Account()

    cursor = cr.execute(
        "SELECT * FROM ACCOUNT WHERE SITE_NAME = ? AND USER_ID = ?", (
            siteName,
            userId,
        ))
    datas = cursor.fetchone()

    if datas:
        acc.Id = datas[0]
        acc.UserId = datas[1]
        acc.SiteName = datas[2]
        acc.SiteAddres = datas[3]
        acc.Pass = datas[4]

        return acc
    else:
        return acc
Beispiel #38
0
 def setUp(self):
     '''登录followme系统'''
     datas = {
         "account": webAPIData['account'],
         "password": webAPIData['passwd'],
         "remember": "false"
     }
     signinRes = Auth.signin(
         webAPIData['hostName'] + authData['signin_url'],
         webAPIData['headers'], datas)
     #登录成功,返回200 ok
     self.assertEqual(signinRes.status_code, webAPIData['status_code_200'])
     #保存登录时的token,待登出使用
     self.token = json.loads(signinRes.text)['data']['token']
     #规整headers
     self.tradeHeaders = dict(
         webAPIData['headers'],
         **{webAPIData['Authorization']: webAPIData['Bearer'] + self.token})
     #获取交易token
     self.tradeToken = Account.getToken(self.tradeHeaders,
                                        onlyTokn="true",
                                        printLogs=1)
Beispiel #39
0
def loopback(stock):

    date = pd.read_sql(stock, engine)
    date["trade_date"] = pd.to_datetime(date["trade_date"], format="%Y%m%d")
    date.index = date["trade_date"]
    date.sort_index(ascending=True, inplace=True)
    account = Account.Account(pd.datetime.now())

    def handle_data(account, today_previous, today, today_next):
        history = date[(date["trade_date"] <= pd.to_datetime(today, format="%Y%m%d"))]
        close = history['close']

        macd, signal, _ = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
        try:
            date["low"].loc[today]
        except:
            return

        if macd[-2] < signal[-2] and macd[-1] > signal[-1]:  # MACD上穿Signal,且无持仓
            account.order(today_next, stock, 100, date["open"].loc[today_next])

        elif macd[-2] > signal[-2] and macd[-1] < signal[-1]:  # MACD下穿Signal,且有持仓
            account.order_to(today_next, stock, 0, date["open"].loc[today_next])

    i = 11
    all_list = date["trade_date"].loc[start.strftime("%Y%m%d"):end.strftime("%Y%m%d")]

    while True:
        today_previous = all_list[i - 1]
        today = all_list[i]
        today_next = all_list[i + 1]
        handle_data(account, today_previous, today, today_next)
        if pd.to_datetime(today_next, format="%Y%m%d") == end:
            break
        i += 1

    account.close_all_positions(pd.datetime.now())
    return stock, account.current_positions[stock]["profit"]
Beispiel #40
0
    def change_game_state(self, **state):
        import BigWorld, Avatar, Account
        assert self.mod_tessumod, "Mod must be loaded first before changing game state"

        if state["mode"] == "battle":
            BigWorld.player(Avatar.Avatar())
            if "players" in state:
                for player in state["players"]:
                    vehicle_id = random.randint(0, 1000000)
                    dbid = random.randint(0, 1000000)
                    BigWorld.player().arena.vehicles[vehicle_id] = {
                        "accountDBID": dbid,
                        "name": player["name"],
                        "isAlive": True
                    }
                    if vehicle_id not in BigWorld.entities:
                        BigWorld.entities[vehicle_id] = BigWorld.Entity()
                    if "position" in player:
                        BigWorld.player(
                        ).arena.positions[vehicle_id] = player["position"]
                        BigWorld.entities[
                            vehicle_id].position = BigWorld.Vector(
                                *player["position"])
            if "camera" in state:
                if "position" in state["camera"]:
                    BigWorld.camera().position = BigWorld.Vector(
                        *state["camera"]["position"])
                if "direction" in state["camera"]:
                    BigWorld.camera().direction = BigWorld.Vector(
                        *state["camera"]["direction"])
        elif state["mode"] == "lobby":
            BigWorld.player(Account.PlayerAccount())
            if "players" in state:
                for id, player in enumerate(state["players"]):
                    BigWorld.player().prebattle.rosters[0][id] = {
                        "name": player["name"],
                        "dbID": random.randint(0, 1000000)
                    }
Beispiel #41
0
def verify():
    #TODO refactor to use exceptions
    if (request.method == "GET"):
        #Two files to choose from based on html query strings
        #Success
        #Failure
        #Expecting two query strings, user id, and autogenerated verification code
        if (request.args):
            #get query strings
            args = request.args
            userId = args.get("id")
            code = args.get("verify")
            #check if query strings are present
            if (userId and code):
                #verify the user
                if (Account.verifyUser(userId, code)):
                    return send_file("templates/verify/success.html")
                else:
                    return send_file("templates/verify/fail.html")
            else:
                return send_file("templates/verify/fail.html")
        else:
            return send_file("templates/verify/fail.html")
Beispiel #42
0
 def submit(self,event):
     if self.uu_id.GetValue()=="" or self.uu_id.GetValue()=="null":
         self.uuid="0"
     else:
         self.uuid=self.uu_id.GetValue()
     self.em=Employee.Myclass(self.ee_id.GetValue(),self.e_name.GetValue(),self.e_address.GetValue(),
                              ChangeDetailPanel.payment,self.uuid,ChangeDetailPanel.mode,self.ems[0][6],self.ems[0][7],self.ems[0][8])
     self.emdao=EmployeeDaoImpl.MyClass()
     self.emdao.delEmpl(self.ems[0][0])
     self.emdao.addEmpl(self.em)
     
     if  ChangeDetailPanel.payment=="pickup":
         pass
     else:
         if self.account.Name=="e_account":
             self.acc=Account.MyClass(self.ee_id.GetValue(),self.account.GetValue())
             self.accdao=AccountDaoImpl.MyClass()
             self.accdao.delAccById(self.ee_id.GetValue())
             self.accdao.addAcc(self.acc)
     
     self.Destroy()
     ListOfEmplPanel(frame)
     frame.Refresh()
def game(num, money):
    number = int(num)
    gen = int(random.randint(0, 10))
    print("====================================")
    print("The roulette landed on ", gen)
    if (gen == 0) and (number == 0):
        jackpot = 14 * money
        print("====================================")
        print("You won ", jackpot, "from green!")
        print(number, "is your number")
        win.winBal(jackpot)
        pass
    elif (gen > 0 and gen < 6) and (number > 0 and number < 6):
        print("====================================")
        print("You won", money, "from red!")
        print(number, "is your number")
        win.winBal(money)

    else:
        print("====================================")
        print("You lost ", money, "!")
        win.winBal(-1 * money)
Beispiel #44
0
    def createAccount(self, name):

        #         if self.findAccount(name) is not None:
        #             raise ValueError("Account with name already exist.")

        self.accounts.append(Account.account(name))
 def test_bad_account_(self):
     bad_client = Client.get_client('mustafa') # from the lion-king
     details = Account.get_details(bad_client)
     self.assertEquals(details, None)
 def test_show_account_with_a_valid_account(self): 
     client = Client.get_client('tsuralik') 
     retVal = Account.show_account(client)
     self.assertEquals(retVal, None)
Beispiel #47
0
 def getKey(self, full_alias):
     simplified = Account.simplifyAlias(full_alias)
     for key in self.map_alias_to_title.keys():                
         if (simplified.find(key) == 0):
             return key
     return 'KEYNOTFOUND'
 def test_get_account_with_invalid_client(self):
     retVal = Account.get_details('string')
     self.assertEquals(retVal, None)
Beispiel #49
0
    def test_UpdatePendingOrder(self):
        '''登录->切换到MT4账号->获取交易token->新建一个挂单->修改挂单的止损止盈->退出登录'''
        userData['headers'][
            userData['Authorization']] = userData['Bearer'] + self.token
        # 获取交易员的accountindex
        self.tradeAccountIndex = Account.getSpecialAccountIndex(
            headers=userData['headers'], brokerID=5)
        # 切换到MT4账号
        switchAccountRes = Account.switchAccount(
            userData['hostName'] + userDataAccount['switchAccount'],
            userData['headers'], self.tradeAccountIndex[0])
        self.assertEqual(switchAccountRes.status_code,
                         userData['status_code_200'])

        # 获取交易token
        getTokenRes = Trade.getToken(
            userData['hostName'] + userDataAccount["getToken_url"],
            userData['headers'])
        FMCommon.printLog('getTokenRes: ' + getTokenRes.text)
        self.assertEqual(getTokenRes.status_code, userData['status_code_200'])
        tradeToken = str(json.loads(
            getTokenRes.content)["data"]["Token"]).replace("=", "@")

        # 开仓获取开仓价格
        openParam = {
            userDataWebSocket['orderParam_cmd']:
            userDataWebSocket['order_cmd'],
            userDataWebSocket['orderParam_code']:
            userDataWebSocket['ws_code_210'],
            userDataWebSocket['orderParam_symbol']: "AUDCAD",
            userDataWebSocket['orderParam_volume']: 1
        }
        openPositionRes = TradeOnline.OnlineTradeEvent.tradeEvent(
            self, userDataWebSocket['ws_host'], userDataWebSocket['ws_port'],
            {'token': "" + tradeToken}, openParam)
        self.assertEqual(openPositionRes["code"],
                         userDataWebSocket['ws_code_0'])
        self.assertEqual(openPositionRes["rcmd"],
                         userDataWebSocket['ws_code_210'])
        self.orderID = openPositionRes["order"]["order_id"]
        self.price = openPositionRes["order"]["price"]

        # 建立挂单
        createPendParam = {
            userDataWebSocket['orderParam_code']:
            userDataWebSocket['ws_code_213'],
            userDataWebSocket['pendingParam_price']:
            self.price + userDataWebSocket['points'],
            userDataWebSocket['orderParam_symbol']:
            "AUDCAD",
            userDataWebSocket['pendingParam_volume']:
            1
        }
        createPendingRes = TradeOnline.OnlineTradeEvent.tradeEvent(
            self, userDataWebSocket['ws_host'], userDataWebSocket['ws_port'],
            {'token': "" + tradeToken}, createPendParam)
        self.assertEqual(createPendingRes["code"],
                         userDataWebSocket['ws_code_0'])
        self.assertEqual(createPendingRes["rcmd"],
                         userDataWebSocket['ws_code_213'])
        self.assertEqual(createPendingRes["order"]["symbol"], "AUDCAD")
        self.assertEqual(createPendingRes["order"]["volume"], 1)
        self.pending = createPendingRes["order"]["order_id"]

        time.sleep(2)
        # 修改挂单(修改止损止盈)
        updatePendingParam = {
            userDataWebSocket['orderParam_code']:
            userDataWebSocket['ws_code_215'],
            userDataWebSocket['orderParam_sl']:
            self.price - userDataWebSocket['points'],
            userDataWebSocket['orderParam_sub_cmd']:
            userDataWebSocket['orderParam_subcmd'],
            userDataWebSocket['orderParam_symbol']:
            "AUDCAD",
            userDataWebSocket['orderParam_ticket']:
            self.pending,
            userDataWebSocket['orderParam_tp']:
            self.price + userDataWebSocket['tp_points'],
            userDataWebSocket['orderParam_volume']:
            userDataWebSocket['pending_volume']
        }
        createPendingRes = TradeOnline.OnlineTradeEvent.tradeEvent(
            self, userDataWebSocket['ws_host'], userDataWebSocket['ws_port'],
            {'token': "" + tradeToken}, updatePendingParam)
        self.assertEqual(createPendingRes["code"],
                         userDataWebSocket['ws_code_0'])
        self.assertEqual(createPendingRes["rcmd"],
                         userDataWebSocket['ws_code_215'])
        self.assertEqual(createPendingRes["order"]["order_id"], self.pending)
        self.assertEqual(createPendingRes["order"]["volume"], 1)
        self.assertEqual(createPendingRes["order"]["symbol"], "AUDCAD")
        self.assertEqual(createPendingRes["order"]["cmd"],
                         userDataWebSocket['pending_cmd'])

        time.sleep(2)
        # 删除挂单
        deletePendParam = {
            userDataWebSocket['orderParam_code']:
            userDataWebSocket['ws_code_214'],
            userDataWebSocket['orderParam_ticket']: self.pending
        }
        deletePendRes = TradeOnline.OnlineTradeEvent.tradeEvent(
            self, userDataWebSocket['ws_host'], userDataWebSocket['ws_port'],
            {'token': "" + tradeToken}, deletePendParam)
        self.assertEqual(deletePendRes["code"], userDataWebSocket['ws_code_0'])
        self.assertEqual(deletePendRes["rcmd"],
                         userDataWebSocket['ws_code_214'])
        self.assertEqual(deletePendRes["order"]["order_id"], self.pending)

        # 平仓
        closeOrder = {
            userDataWebSocket['orderParam_code']:
            userDataWebSocket['ws_code_211'],
            userDataWebSocket['orderParam_ticket']: self.orderID,
            userDataWebSocket['orderParam_volume']: 1
        }
        closeOrderRes = TradeOnline.OnlineTradeEvent.tradeEvent(
            self, userDataWebSocket['ws_host'], userDataWebSocket['ws_port'],
            {'token': "" + tradeToken}, closeOrder)
        self.assertEqual(closeOrderRes["code"], userDataWebSocket['ws_code_0'])
        self.assertEqual(closeOrderRes["rcmd"],
                         userDataWebSocket['ws_code_211'])
        self.assertEqual(closeOrderRes['order']["order_id"], self.orderID)
        self.assertEqual(closeOrderRes["order"]["volume"], 1)
 def post(self):
     Account.log_in(self)
    def test_KVBFollowSam(self):
        '''Sam账户跟随福汇交易员'''
        userData['headers'] = dict(
            userData['headers'],
            **{'Authorization': userData['Bearer'] + self.token})
        self.traderHeaders = dict(
            userData['headers'],
            **{'Authorization': userData['Bearer'] + self.traderToken})

        # 获取交易员账户的AccountIndex
        self.tradeAccountIndex = Account.getSpecialAccountIndex(
            headers=self.traderHeaders, brokerID=5)
        # 获取sam账户的AccountIndex
        self.followerSamAccountIndex = Account.getSpecialAccountIndex(
            headers=userData['headers'], accountType=2, brokerID=106)

        # 新建一个跟随,固定手数跟随
        params = {
            "accountIndex": int(self.followerSamAccountIndex[0]),
            "strategy": "fixed",
            "setting": 1.5,
            "direction": "positive"
        }
        getFollowsRes = Follow.createFollow(
            userData['hostName'] + userDataFollow["Follow_Url"] +
            str(self.traderUserId) + "_" + self.tradeAccountIndex[0],
            headers=userData['headers'],
            datas=params)
        FMCommon.printLog('getFollowsRes: ' + getFollowsRes.text)
        self.assertEqual(getFollowsRes.status_code,
                         userData['status_code_200'])

        #交易员切换账户
        Account.switchAccount(
            userData['hostName'] + userDataAccount['switchAccount'],
            self.traderHeaders, self.tradeAccountIndex[0])

        # 获取交易员交易token
        traderTokenRes = Trade.getToken(
            userData['hostName'] + userDataAccount["getToken_url"],
            self.traderHeaders)
        self.assertEqual(traderTokenRes.status_code,
                         userData['status_code_200'])
        tradeToken = str(json.loads(
            traderTokenRes.content)["data"]["Token"]).replace("=", "@")

        # 交易员开仓
        openParam = {
            userDataWebSocket['orderParam_code']:
            userDataWebSocket['ws_code_210'],
            userDataWebSocket['orderParam_symbol']: "EURCAD",
            userDataWebSocket['orderParam_volume']: 1000
        }
        openPositionRes = TradeOnline.OnlineTradeEvent.tradeEvent(
            self, userDataWebSocket['ws_host'], userDataWebSocket['ws_port'],
            {'token': "" + tradeToken}, openParam)
        FMCommon.printLog(openPositionRes)
        self.assertEqual(openPositionRes["code"],
                         userDataWebSocket['ws_code_0'])
        self.assertEqual(openPositionRes["rcmd"],
                         userDataWebSocket['ws_code_210'])
        self.assertEqual(openPositionRes["order"]["volume"], 1000)
        self.orderID = openPositionRes["order"]["order_id"]

        # 交易员平仓
        closeOrder = {
            userDataWebSocket['orderParam_code']:
            userDataWebSocket['ws_code_211'],
            userDataWebSocket['orderParam_ticket']: self.orderID,
            userDataWebSocket['orderParam_volume']: 1000
        }
        closeOrderRes = TradeOnline.OnlineTradeEvent.tradeEvent(
            self, userDataWebSocket['ws_host'], userDataWebSocket['ws_port'],
            {'token': "" + tradeToken}, closeOrder)
        FMCommon.printLog(closeOrderRes)
        self.assertEqual(closeOrderRes["code"], userDataWebSocket['ws_code_0'])
        self.assertEqual(closeOrderRes["rcmd"],
                         userDataWebSocket['ws_code_211'])
        self.assertEqual(closeOrderRes['order']["order_id"], self.orderID)
        self.assertEqual(closeOrderRes["order"]["volume"], 1000)

        # 查询交易员的历史订单
        time.sleep(userDataWebSocket['waitTime'])
        historyOrdersRes = Trade.getOrders(
            userData['hostName'] + userDataTrade["getOrders"],
            self.traderHeaders, userData['orderStatus_close'])
        self.assertEqual(historyOrdersRes.status_code,
                         userData['status_code_200'])
        self.assertIn(
            str(self.orderID),
            str(json.loads(historyOrdersRes.content)["data"]["items"]))
        FMCommon.printLog('historyOrdersRes: ' + historyOrdersRes.text)

        # 跟随者切换账户
        Account.switchAccount(
            userData['hostName'] + userDataAccount['switchAccount'],
            userData['headers'], self.followerSamAccountIndex[0])

        # 获取跟随者交易token
        followertokenRES = Trade.getToken(
            userData['hostName'] + userDataAccount["getToken_url"],
            userData['headers'])
        self.assertEqual(followertokenRES.status_code,
                         userData['status_code_200'])
        MT4Account = str(
            json.loads(followertokenRES.content)["data"]["MT4Account"])

        #  验证跟随者跟单成功
        sql = "SELECT TradeID from t_followorder where Account=" + MT4Account + " and TraderTradeID=" + str(
            self.orderID)
        row = FollowOperation.Operation.operationCopytradingDB(sql)

        # 查询跟随者的历史订单
        followerHistoryOrdersRes = Trade.getOrders(
            userData['hostName'] + userDataTrade["getOrders"],
            userData['headers'], userData['orderStatus_close'])
        self.assertEqual(followerHistoryOrdersRes.status_code,
                         userData['status_code_200'])
        self.assertIn(
            str(row['TradeID']),
            str(json.loads(followerHistoryOrdersRes.content)["data"]["items"]))

        # 取消跟随
        cancelFollowRes = Follow.DeleteFollow(
            userData['hostName'] + userDataFollow["Follow_Url"] +
            str(self.traderUserId) + "_" + self.tradeAccountIndex[0] +
            "?accountIndex=" + self.followerSamAccountIndex[0],
            userData['headers'])
        FMCommon.printLog('cancelFollowRes: ' + cancelFollowRes.text)
        self.assertEqual(cancelFollowRes.status_code,
                         userData['status_code_200'])
Beispiel #52
0
    else:
        return False

def get_link_and_title(submission):
    link = submission.url
    title = submission.title
    return link, title

def get_nth_submission(submissions, n):
    while n >= 0:
        submission = next(submissions)
        n = n-1
    return get_link_and_title(submission)

### Account authentication
r = Account.login()

### Define subreddits
gb = r.get_subreddit('gentlemanboners')
til = r.get_subreddit('todayilearned')
kbs = r.get_subreddit('knowledgebombshell')

### Get random numbers to draw pics 
pic_num = random.randint(0,9)
fact_num = random.randint(1,10)

gb_top15 = gb.get_hot(limit=15)
til_top15 = til.get_hot(limit=15)

pic_link, pic_title = get_nth_submission(gb_top15, pic_num)
fact_link, fact_title = get_nth_submission(til_top15, fact_num)
Beispiel #53
0
    def test_Follows(self):
        '''登录->新建一个跟随->获取指定交易员存在的跟随关系->修改一个跟随->取消跟随'''
        userData['headers'] = dict(
            userData['headers'],
            **{'Authorization': userData['Bearer'] + self.token})
        self.traderHeaders = dict(
            userData['headers'],
            **{'Authorization': userData['Bearer'] + self.traderToken})

        # 获取交易员的accountindex
        self.tradeAccountIndex = Account.getSpecialAccountIndex(
            headers=self.traderHeaders, brokerID=5)

        # 获取跟随者的accountindex
        self.followerAccountIndex = Account.getSpecialAccountIndex(
            headers=userData['headers'], brokerID=5)

        # 新建一个跟随,固定手数跟随
        params = {
            "accountIndex": int(self.followerAccountIndex[0]),
            "strategy": "fixed",
            "setting": 1.5,
            "direction": "positive"
        }
        getFollowsRes = Follow.createFollow(
            userData['hostName'] + userDataFollow["Follow_Url"] +
            str(self.traderUserId) + "_" + self.tradeAccountIndex[0],
            headers=userData['headers'],
            datas=params)
        FMCommon.printLog('getFollowsRes: ' + getFollowsRes.text)
        self.assertEqual(getFollowsRes.status_code,
                         userData['status_code_200'])

        # 跟随者切换账户
        Account.switchAccount(
            userData['hostName'] + userDataAccount['switchAccount'],
            userData['headers'], self.followerAccountIndex[0])

        # 获取跟随者交易token
        demotoken = Trade.getToken(
            userData['hostName'] + userDataAccount["getToken_url"],
            userData['headers'])
        self.assertEqual(demotoken.status_code, userData['status_code_200'])
        followerMT4Account = str(
            json.loads(demotoken.content)["data"]["MT4Account"])

        # 获取指定交易员存在的跟随关系
        getTraderFollowRes = Follow.getFollow(
            userData['hostName'] + userDataFollow["Follow_Url"],
            str(self.traderUserId) + "_" + self.tradeAccountIndex[0],
            self.followerAccountIndex[0], userData['headers'])
        FMCommon.printLog('getTraderFollowRes: ' + getTraderFollowRes.text)
        self.assertEqual(getTraderFollowRes.status_code,
                         userData['status_code_200'])
        FollowAccount = json.loads(
            getTraderFollowRes.text)['data']['follow']['FollowAccount']
        self.assertEqual(FollowAccount, followerMT4Account, "没有包含此跟随者")

        # 修改一个跟随(修改跟随策略)
        params = {
            "accountIndex": int(self.followerAccountIndex[0]),
            "strategy": "ratio",
            "setting": 2,
            "direction": "positive"
        }
        updateFollowRes = Follow.updateFollow(
            userData['hostName'] + userDataFollow["Follow_Url"] +
            str(self.traderUserId) + "_" + self.tradeAccountIndex[0],
            userData['headers'],
            datas=params)
        FMCommon.printLog('updateFollowRes: ' + updateFollowRes.text)
        self.assertEqual(updateFollowRes.status_code,
                         userData['status_code_200'])

        # 取消跟随
        cancelFollowRes = Follow.DeleteFollow(
            userData['hostName'] + userDataFollow["Follow_Url"] +
            str(self.traderUserId) + "_" + self.tradeAccountIndex[0] +
            "?accountIndex=" + self.followerAccountIndex[0],
            userData['headers'])
        FMCommon.printLog('cancelFollowRes: ' + cancelFollowRes.text)
        self.assertEqual(cancelFollowRes.status_code,
                         userData['status_code_200'])
 def test_get_account_with_no_client(self):
     retVal = Account.get_details(None)
     self.assertEquals(retVal, None)