def classifyUser(): # token = request.form["ori_token"] customer = Account(token) return jsonify({ "customer_category": customer.predictUserType() })
def rewardBalance(): # token = request.form["ori_token"] customer = Account(token) return jsonify({ "reward_balance": customer.getRewardBalance() })
def generate_accounts(self): accounts = [] alignment_list = [] num_aligned = int(self.num_accounts * self.num_opps * self.alignment) for idx in range(1, (self.num_accounts * self.num_opps) + 1): alignment_list.append(True if idx < num_aligned else False) random.shuffle(alignment_list) for idx in range(1, self.num_accounts + 1): name = self.lipsum.get_name() account = Account(self.acc_size_list, self.location_list, self.num_opps, self.alignment, alignment_list[((idx - 1) * self.num_opps):(idx * self.num_opps)], self.p1_devs, self.p2_devs, self.opp_sizes, self.pid, self.last_acc_id, self.last_opp_id, self.last_fact_id, name, self.partner_driven) last_ids = account.get_last_ids() self.last_acc_id = last_ids['acc_id'] self.last_opp_id = last_ids['opp_id'] self.last_fact_id = last_ids['fact_id'] accounts.append(account) return accounts
def main(): parser = argparse.ArgumentParser() common.config.add_argument(parser) args = parser.parse_args() account_id = args.config.active_account api = args.config.create_context() response = api.account.get(account_id) account = Account(response.get('account', '200')) account.dump()
def canBuy(): # token = request.form["ori_token"] product_url = request.form["product_url"] customer = Account(token) product = Product(product_url) return jsonify({ "buy_status": customer.canBuyUsingDebit(product), "buy_classification": customer.predictUserType() })
def test_account_returns_data_for_id_1(self): # Given account_data = {"id": "1", "name": "test"} mock_data_interface = Mock() mock_data_interface.get.return_value = account_data # When account = Account(data_interface=mock_data_interface) # Then self.assertEqual(account_data, account.get_account(1))
def test_account_when_connect_exception_raised(self): # Given mock_data_interface = Mock() mock_data_interface.get.side_effect = ConnectionError() # When account = Account(data_interface=mock_data_interface) # Then self.assertEqual("Connection error occurred. Try again.", account.get_account(1))
def test_get_current_balance_returns_data_correctly(self, mock_requests): # Given # mock a response and force that to be the return value mock_response = Mock() mock_response.status_code = '200' mock_response.text = 'Some text data' mock_requests.get.return_value = mock_response # When account = Account(Mock()) # Then self.assertEqual(account.get_current_balance(1), { 'status': '200', 'data': 'Some text data' })
def test_empty_validator_pass(self): account = Account() validator = Validator() violations = validator.validate(account, {}) self.assertEqual(violations, [])
def test_create_account_constraint_pass(self): account = Account() validator = Validator(CreateAccount()) event = {"account": {"activeCard": "true", "availableLimit": 100}} violations = validator.validate(account, event) self.assertEqual(violations, [])
def save_asset_Valuation(accountType='0', currency='USD'): config = ReadConfig() # 初始化数据库连接 engine = create_engine(config.get_dbURL()) okex_api_key = config.get_okex("OKEX_API_KEY") okex_secret_key = config.get_okex("OKEX_SECRET_KEY") okex_passphrase = config.get_okex("OKEX_PASSPHRASE") spotAPI = spot.SpotAPI(okex_api_key, okex_secret_key, okex_passphrase, False) accountAPI = account.AccountAPI(okex_api_key, okex_secret_key, okex_passphrase, False) accountClient = Account(spotAPI, accountAPI, engine) now = datetime.datetime.now() asset = pd.DataFrame(columns=[ 'account_type', 'balance', 'valuation_currency', 'timestamp', 'ts' ], index=[0]) res = accountClient.get_okex_asset_valuation(accountType, currency) print(res) accountClient.save_okex_asset_valuation(res) return """ <h1>更新资产完成</h1> <p>/assetValuation</p> <p>/assetValuation/accountType</p> <p>/assetValuation/accountType/currency</p> <p>0:预估总资产</p> <p>1:币币账户</p> <p>3:交割账户</p> <p>5:币币杠杆</p> <p>6:资金账户</p> <p>9:永续合约</p> <p>12:期权</p> <p>15:交割usdt保证金账户</p> <p>16:永续usdt保证金账户</p> <p>{}</p> """.format(res)
def setUp(self): self.account = Account() self.accountmanager = AccountManager(self.account) self.constraints = Constraint() self.constraints \ .set_next(CreateAccount()) \ .set_next(ActiveCard()) \ .set_next(InsufficientLimit()) \ .set_next(HighFrequencySmallInterval()) \ .set_next(DoubledTransaction()) \
def process_transaction(self, event): id = event['id'] if not self.account_exists(id): return Account(), ['account-doesnt-exist'] violations = self.validator.validate(self.accounts[id], self.event) self.accounts[id].available_limit -= event['amount'] self.accounts[id].logs.append({ 'merchant': event['merchant'], 'time': event['time'] }) return self.accounts[id], violations
def process_creation(self, event): id = event['id'] violations = [] if self.account_exists(id): violations = self.validator.validate(self.accounts[id], self.event) return self.accounts[id], violations account = Account() account.created = True account.id = event['id'] account.active_card = event['activeCard'] account.available_limit = event['availableLimit'] self.accounts[id] = account return account, violations
def main(): """Main Method.""" user = Account() user.statement()
def placeOrder(pair, signal): #Check if trade is already open for pai #pair="EUR_GBP" #signal="sell" risk = 0.015 parser = argparse.ArgumentParser() common.config.add_argument(parser) args = parser.parse_args() account_id = args.config.active_account api = args.config.create_context() kwargs = {} response = api.account.get(account_id) ac = response.get("account", "200") account1 = Account(ac) account1.dump() accountBalance = account1.details.balance tradeCount = account1.details.openTradeCount trades = account1.position_get(pair) # sellTrades=trades.short.tradeIDs # buyTrades=trades.long.tradeIDs #if trades.short.units<0 or trades.long.units>0: kwargs = {} kwargs["instruments"] = pair kwargs["since"] = None kwargs["includeUnitsAvailable"] = "FALSE" kwargs["includeHomeConversions"] = "FALSE" response = api.pricing.get(account_id, **kwargs) price = response.get("prices", 200) bid = price[0].bids[0].price ask = price[0].asks[0].price spread = ask - bid mid = (ask + bid) / 2 if signal == "buy": stoploss = bid - 2 * spread takeProfit = bid + 2 * spread potentialLoss = 3 * spread sign = 1 convert = price[0].quoteHomeConversionFactors.positiveUnits elif signal == "sell": stoploss = ask + 2 * spread takeProfit = ask - 2 * spread potentialLoss = 3 * spread sign = -1 convert = price[0].quoteHomeConversionFactors.negativeUnits # #ac=response.get("price", "200") # #candles = response.get("candles", 200) # # # stoploss=round(stoploss,8) # takeProfit=round(takeProfit,8) # # position size * change *conversion factor/traded currency = account balance * risk positionsize = ((risk * accountBalance) * mid) / (potentialLoss) positionsize = int(positionsize) kwargs = {} kwargs1 = {} kwargs1["price"] = stoploss #self.parsed_args["stopLossOnFill"] = \ #kwargs["id"] = 123456 kwargs["instrument"] = pair kwargs["units"] = sign * positionsize kwargs["type"] = "MARKET" kwargs["stopLossOnFill"] = v20.transaction.StopLossDetails(**kwargs1) kwargs1["price"] = takeProfit kwargs["takeProfitOnFill"] = v20.transaction.TakeProfitDetails(**kwargs1) #marketOrderArgs.parse_arguments(args) order = api.order.market(account_id, **kwargs) #order=api.order.MarketOrder(order) #print("Response: {} ({})".format(order.status, order.reason)) #print("")re #Check if trade is in same direction as current trade #Prematurely close previous trade if signal is in opposite direction? #Load panda #Remove any old trades from Panda database (i.e. if stop has been triggered) #Calculate spread #Calculate volitility #Calculate initial stoploss #Place trade #record trade to Panda along with target value at which new stop will be implemented #i.e. when When profit reaches x2 the spread, #set stop loss to 1.5x the spread, if reaches x3 the spread, set trialling stop loss to x1 spread distance #save panda to file return
#Check if trade is already open for pai pair = "AUD_JPY" signal = "sell" risk = 0.01 parser = argparse.ArgumentParser() common.config.add_argument(parser) args = parser.parse_args() account_id = args.config.active_account api = args.config.create_context() kwargs = {} response = api.account.get(account_id) ac = response.get("account", "200") account1 = Account(ac) #account1.dump() accountBalance = account1.details.balance tradeCount = account1.details.openTradeCount trades = account1.position_get(pair) # sellTrades=trades.short.tradeIDs # buyTrades=trades.long.tradeIDs #if trades.short.units<0 or trades.long.units>0: kwargs = {} kwargs["instruments"] = pair kwargs["since"] = None kwargs["includeUnitsAvailable"] = "FALSE" kwargs["includeHomeConversions"] = "TRUE" #kwargs["granularity"] = "M15"
def new_account(self, status, balances): account_key = str(uuid.uuid4().hex)[:8] account_private = str(uuid.uuid4().hex)[:10] self.accounts[account_key] = Account(account_key, account_private, balances, status) return account_key, account_private
from user.user import User from account.account import Account if __name__ == "__main__": print() account = Account(input("Enter Bank Name : "), input("Enter Branch Name : ")) choice = True while True: print() user = User(input("Enter the name of the Account Holder : ")) print() account.addAccount(user.registerUser()) print() choice = input("Press 'Y' to add more Users : ") if choice == 'y' or choice == 'Y': continue else: break print() print() account.listAllAccounts() print() account.deleteAccount( input( "Enter the name of the account holder whose account you want to delete : "
def account(): """Return an Account object.""" return Account()
from order.args import OrderArguments #import datetime #while 1: #def modifyOrder(pair, signal): parser = argparse.ArgumentParser() common.config.add_argument(parser) args = parser.parse_args() account_id = args.config.active_account api = args.config.create_context() kwargs = {} response = api.account.get(account_id) ac = response.get("account", "200") account1 = Account(ac) kwargs = {} kwargs1 = {} #kwargs1["price"] = #kwargs["id"]="282" # kwargs["units"]=10 # kwargs["type"]="MARKET" #kwargs["stopLoss"]=v20.transaction.StopLossDetails(**kwargs1) kwargs1["price"] = None #kwargs["takeProfit"]=v20.transaction.TakeProfitDetails(**kwargs1) kwargs1["distance"] = None #kwargs["trailingStopLoss"]=v20.transaction.TrailingStopLossDetails(**kwargs1) kwargs["trailingStopLoss"] = None #marketOrderArgs.parse_arguments(args)
def setUp(self): self.account = Account() self.account.created = True self.account.active_card = True self.account.available_limit = 100
def getBalance(): # token = request.form["ori_token"] customer = Account(token) return jsonify(customer.getBalance())
def investmentsSummary(): customer = Account(token) return jsonify(customer.getInvestmentsSummary())