买入卖出股票
        :param security: 股票代码
        :param price: 买入价格
        :param amount: 买入股数
        :param volume: 买入总金额 由 volume / price 取整， 若指定 price 则此参数无效
        :param entrust_prop:
180852
def buy(self, security, price=0, amount=0, volume=0, entrust_prop=0):
        
        return self._trade(security, price, amount, volume, "buy")
312337
def sign(conf):
    """"""
    try:
        v2ex = V2ex(conf.config)
        v2ex.login()
        balance = v2ex.get_money()
        click.echo(balance)
    except KeyError:
        click.echo('Keyerror, please check your config file.')
    except IndexError:
        click.echo('Please check your username and password.')
1351522
function strategy (options, verify) {

  // some sensible defaults
  options.protocol = options.protocol || 'https://';
  options.signatureAlgorithm = options.signatureAlgorithm || 'sha256';
  options.identifierFormat = options.identifierFormat || 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient';
  options.acceptedClockSkewMs = options.acceptedClockSkewMs || 60000;
  options.attributeConsumingServiceIndex = options.attributeConsumingServiceIndex || false;
  options.forceAuthn = options.forceAuthn || false;
  options.skipRequestCompression = options.skipRequestCompression || false;

  if (options.disableRequestedAuthnContext === undefined) {
    options.disableRequestedAuthnContext = true;
  }

  if (options.validatedInResponseTo === undefined) {
    options.validateInResponseTo = true;
  }

  if (options.decryptionCertPath) {
    options.decryptionCert = fs.readFileSync(options.decryptionCertPath, 'utf8');
  }

  if (options.decryptionPvkPath) {
    options.decryptionPvk = fs.readFileSync(options.decryptionPvkPath, 'utf8');
  }

  if (options.entityID) {
    options.issuer = options.entityID;
  }

  if (options.entityId) {
    options.issuer = options.entityId;
  }

  if (options.idp) {
    if (idps[options.idp]) {
      options.entryPoint = idps[options.idp].entryPoint;
      options.cert = idps[options.idp].cert;
    } else {
      throw new Error('Unknown IdP: ' + options.idp);
    }
  }

  if (!options.entryPoint || !options.cert) {
    console.warn('No IdP defined - defaulting to ' + idps.dev.entityID);
    options.entryPoint = idps.dev.entryPoint;
    options.cert = idps.dev.cert;
  }

  if (!options.issuer) {
    throw new Error('No entityId defined!');
  }

  // having either both an encryption cert and private key is valid
  // having neither an encryption cert nor a private key is also valid
  // having only one or the other is NOT valid
  if (!options.decryptionCert && options.decryptionPvk) {
    throw new Error('Only a private key was defined; a public cert is also required');
  }

  if (options.decryptionCert && !options.decryptionPvk) {
    throw new Error('Only a public cert was defined; a private key is also required')
  }

  if (!options.loginPath) {
    throw new Error('No loginPath defined!');
  }

  this.loginPath = options.loginPath;

  // set up an attribute mapper
  this.attributeMapper = attrmap(options.attributeMap);

  // call the parent method before setting the strategy name,
  // otherwise the name will always be 'saml'
  saml.Strategy.call(this, options, function (req, profile, done) {
    req.session.strategy = this.name;
    this.attributeMapper(profile, done);
  }.bind(this));

  // set the name of this strategy to either the name passed in
  // via the options, or the short name of the idp.
  //
  // if neither is set, the name will be 'suSAML'

  this.name = options.name || options.idp || 'suSAML';

}
152013
def _calculate_order_value_amount(self, asset, value):
        
        if not self.executor.current_data.can_trade(asset):
            raise CannotOrderDelistedAsset(
                msg="Cannot order {0}, as it not tradable".format(asset.symbol)
            )

        last_price = \
            self.executor.current_data.current(asset, "price")

        if np.isnan(last_price):
            raise CannotOrderDelistedAsset(
                msg="Cannot order {0} on {1} as there is no last "
                    "price for the security.".format(asset.symbol,
                                                     self.datetime)
            )

        if tolerant_equals(last_price, 0):
            zero_message = "Price of 0 for {psid}; can't infer value".format(
                psid=asset
            )
            log.debug(zero_message)
            # Don't place any order
            return 0

        return value / last_price
958113
def buy_market_order(self, amount, base="btc", quote="usd"):
        
        data = {'amount': amount}
        url = self._construct_url("buy/market/", base, quote)
        return self._post(url, data=data, return_json=True, version=2)
877763
async def write_deal(self, **params):
		
		if params.get("message"):
			params = json.loads(params.get("message", "{}"))
		
		if not params:
			return {"error":400, "reason":"Missed required fields"}

		cid = int(params.get("cid", 0))
		access_type = params.get("access_type")
		buyer = params.get("buyer")
		seller = params.get("seller")
		price = params.get("price")
		coinid = params.get("coinid")

		try:
			coinid = coinid.replace("TEST", "")
		except:
			pass

		if not all([cid, access_type, buyer, seller, price]):
			return {"error":400, "reason":"Missed required fields"}

		database = client[coinid]
		collection = database[settings.DEAL]
		await collection.insert_one({
				"cid":cid,
				"access_type": access_type,
				"buyer":buyer,
				"seller":seller,
				"price":price,
				"coinid":coinid
			})
		result = await collection.find_one({"cid":cid, "buyer":buyer})

		return {i:result[i] for i in result if i != "_id"}
323257
def get_aggregate(self, security: Commodity) -> SecurityAggregate:
        
        assert security is not None
        assert isinstance(security, Commodity)

        return SecurityAggregate(self.book, security)
993959
def auth(self, value):
        
        self._auth = value
        self._request.auth = value
1050727
async def put(self, public_key):
		
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		# Check if message contains required data
		try:
			body = json.loads(self.request.body)
		except:
			self.set_status(400)
			self.write({"error":400, "reason":"Unexpected data format. JSON required"})
			raise tornado.web.Finish
			
		if isinstance(body["message"], str):
			message = json.loads(body["message"])
		elif isinstance(body["message"], dict):
			message = body["message"]
		cid = int(message["offer_id"].get("cid", 0))
		buyer_address = message["offer_id"].get("buyer_address")
		coinid = message.get("coinid")

		if not all([cid, buyer_address, coinid]):
			self.set_status(400)
			self.write({"error":400, "reason": "Missed required fields."})
			raise tornado.web.Finish

		if coinid in settings.bridges.keys():
			self.account.blockchain.setendpoint(settings.bridges[coinid])
		else:
			self.set_status(400)
			self.write({"error":400, "reason":"Invalid coin ID"})
			raise tornado.web.Finish

		check = self.account.validator[coinid](public_key)

		account = await self.account.getaccountdata(public_key=public_key)
		if "error" in account.keys():
			error_code = account["error"]
			self.set_status(error_code)
			self.write(account)
			raise tornado.web.Finish
	
		# Check if one of sellers or buyers rejects offer
		owneraddr = await self.account.blockchain.ownerbycid(cid=cid)
		hex_ = check
		if buyer_address != hex_ and owneraddr != hex_:
			# Avoid rejecting offer
			self.set_status(403)
			self.write({"error": 403, "reason":"Forbidden. Offer does not belong to user."})
		
		# Reject offer
		response = await self.account.blockchain.rejectoffer(coinid=coinid, cid=cid, 
															buyer_address=buyer_address)
		if "error" in response.keys():
			self.set_status(response["error"])
			self.write(response)
			raise tornado.web.Finish

		# Get buyer for email sending
		buyer = await self.account.getaccountbywallet(wallet=buyer_address)
		if "error" in buyer.keys():
			self.set_status(buyer["error"])
			self.write(buyer)
			raise tornado.web.Finish
	
		if buyer.get("email"):
			emaildata = {
				"to": buyer.get("email"),
				"subject": "Robin8 support",
     			"optional": "Your offer with cid %s was rejected." % cid
			}
			await self.account.mailer.sendmail(**emaildata)
		
		# Undeposit balance
		price = await self.account.blockchain.getwriteprice(cid=cid)
		coinid = "PUT"
		await self.account.balance.unfreeze(uid=buyer["id"],coinid=coinid, 
													amount=price)

		del response["result"]
		self.write(response)
558700
def trusted=(val)
      if ! [ true, false ].include?(val)
        raise ArgumentError, "value must be a boolean"
      end
      @o_dev[I_DEVICE]['Trusted'] = val
    end
939125
def verify_invoice_params(self, price, currency):
    
    if re.match("^[A-Z]{3,3}$", currency) is None:
      raise BitPayArgumentError("Currency is invalid.")
    try: 
      float(price)
    except:
      raise BitPayArgumentError("Price must be formatted as a float")
721673
public ElasticsearchContainer withSecureSetting(String key, String value) {
        securedKeys.put(key, value);
        return this;
    }
340740
def buy_market_order(self, amount):
        
        amount = str(amount)
        self._log("buy {} {} at market price".format(amount, self.major))
        return self._rest_client.post(
            endpoint='/buy',
            payload={'book': self.name, 'amount': amount}
        )
907845
def addMov(self, product, quantity=None, mode="buy", stop_limit=None,
               auto_margin=None, name_counter=None):
        """"""
        # ~ ARGS ~
        if (not isinstance(product, type('')) or
                (not isinstance(name_counter, type('')) and
                 name_counter is not None)):
            raise ValueError('product and name_counter have to be a string')
        if not isinstance(stop_limit, type({})) and stop_limit is not None:
            raise ValueError('it has to be a dictionary')
        # exclusive args
        if quantity is not None and auto_margin is not None:
            raise ValueError("quantity and auto_margin are exclusive")
        elif quantity is None and auto_margin is None:
            raise ValueError("need at least one quantity")
        # ~ MAIN ~
        # open new window
        mov = self.new_mov(product)
        mov.open()
        mov.set_mode(mode)
        # set quantity
        if quantity is not None:
            mov.set_quantity(quantity)
            # for best performance in long times
            try:
                margin = mov.get_unit_value() * quantity
            except TimeoutError:
                mov.close()
                logger.warning("market closed for %s" % mov.product)
                return False
        # auto_margin calculate quantity (how simple!)
        elif auto_margin is not None:
            unit_value = mov.get_unit_value()
            mov.set_quantity(auto_margin * unit_value)
            margin = auto_margin
        # stop limit (how can be so simple!)
        if stop_limit is not None:
            mov.set_limit('gain', stop_limit['gain'][0], stop_limit['gain'][1])
            mov.set_limit('loss', stop_limit['loss'][0], stop_limit['loss'][1])
        # confirm
        try:
            mov.confirm()
        except (exceptions.MaxQuantLimit, exceptions.MinQuantLimit) as e:
            logger.warning(e.err)
            # resolve immediately
            mov.set_quantity(e.quant)
            mov.confirm()
        except Exception:
            logger.exception('undefined error in movement confirmation')
        mov_logger.info(f"added {mov.product} movement of {mov.quantity} " +
                        f"with margin of {margin}")
        mov_logger.debug(f"stop_limit: {stop_limit}")
521350
def _calculate_order_value_amount(self, asset, value):
        
        # Make sure the asset exists, and that there is a last price for it.
        # FIXME: we should use BarData's can_trade logic here, but I haven't
        # yet found a good way to do that.
        normalized_date = normalize_date(self.datetime)

        if normalized_date < asset.start_date:
            raise CannotOrderDelistedAsset(
                msg="Cannot order {0}, as it started trading on"
                    " {1}.".format(asset.symbol, asset.start_date)
            )
        elif normalized_date > asset.end_date:
            raise CannotOrderDelistedAsset(
                msg="Cannot order {0}, as it stopped trading on"
                    " {1}.".format(asset.symbol, asset.end_date)
            )
        else:
            last_price = \
                self.trading_client.current_data.current(asset, "price")

            if np.isnan(last_price):
                raise CannotOrderDelistedAsset(
                    msg="Cannot order {0} on {1} as there is no last "
                        "price for the security.".format(asset.symbol,
                                                         self.datetime)
                )

        if tolerant_equals(last_price, 0):
            zero_message = "Price of 0 for {psid}; can't infer value".format(
                psid=asset
            )
            if self.logger:
                self.logger.debug(zero_message)
            # Don't place any order
            return 0

        value_multiplier = asset.price_multiplier

        return value / (last_price * value_multiplier)
315767
def encrypt_password(**kwargs):
    
    new_value = kwargs['new_value']
    field = kwargs['field']
    min_length = field.params['min_length']
    if len(new_value) < min_length:
        raise ValueError(
            '`{}`: Value length must be more than {}'.format(
                field.name, field.params['min_length']))

    if new_value and not crypt.match(new_value):
        new_value = str(crypt.encode(new_value))
    return new_value
223105
def _driver_signing_reg_conversion(cls, val, **kwargs):
        '''
        
        '''
        log.debug('we have %s for the driver signing value', val)
        if val is not None:
            # since this is from secedit, it should be 3,<value>
            _val = val.split(',')
            if len(_val) == 2:
                if _val[1] == '0':
                    return 'Silently Succeed'
                elif _val[1] == '1':
                    return 'Warn but allow installation'
                elif _val[1] == '2':
                    return 'Do not allow installation'
                elif _val[1] == 'Not Defined':
                    return 'Not Defined'
                else:
                    return 'Invalid Value'
            else:
                return 'Not Defined'
        else:
            return 'Not Defined'