Borrow a bitasset/market-pegged asset
481248
def borrow(ctx, amount, symbol, ratio, account):
    
    from bitshares.dex import Dex

    dex = Dex(bitshares_instance=ctx.bitshares)
    print_tx(
        dex.borrow(Amount(amount, symbol), collateral_ratio=ratio, account=account)
    )
350347
def acquire(self):
        """"""
        self.lease = self.client.lease(self.ttl)

        base64_key = _encode(self.key)
        base64_value = _encode(self._uuid)
        txn = {
            'compare': [{
                'key': base64_key,
                'result': 'EQUAL',
                'target': 'CREATE',
                'create_revision': 0
            }],
            'success': [{
                'request_put': {
                    'key': base64_key,
                    'value': base64_value,
                    'lease': self.lease.id
                }
            }],
            'failure': [{
                'request_range': {
                    'key': base64_key
                }
            }]
        }
        result = self.client.transaction(txn)
        if 'succeeded' in result:
            return result['succeeded']
        return False
67936
def feeds(ctx, assets, pricethreshold, maxage):
    
    import builtins

    witnesses = Witnesses(bitshares_instance=ctx.bitshares)

    def test_price(p, ref):
        if math.fabs(float(p / ref) - 1.0) > pricethreshold / 100.0:
            return click.style(str(p), fg="red")
        elif math.fabs(float(p / ref) - 1.0) > pricethreshold / 2.0 / 100.0:
            return click.style(str(p), fg="yellow")
        else:
            return click.style(str(p), fg="green")

    def price_diff(p, ref):
        d = (float(p) - float(ref)) / float(ref) * 100
        if math.fabs(d) >= 5:
            color = "red"
        elif math.fabs(d) >= 2.5:
            color = "yellow"
        else:
            color = "green"
        return click.style("{:8.2f}%".format(d), fg=color)

    def test_date(d):
        t = d.replace(tzinfo=None)
        now = datetime.utcnow()
        if now < t + timedelta(minutes=maxage):
            return click.style(str(t), fg="green")
        if now < t + timedelta(minutes=maxage / 2.0):
            return click.style(str(t), fg="yellow")
        else:
            return click.style(str(t), fg="red")

    output = ""
    for asset in tqdm(assets):
        t = PrettyTable(
            [
                "Asset",
                "Producer",
                "Active Witness",
                "Date",
                "Settlement Price",
                "Core Exchange Price",
                "MCR",
                "SSPR",
                "delta",
            ]
        )
        t.align = "c"
        t.align["Producer"] = "l"
        asset = Asset(asset, full=True, bitshares_instance=ctx.bitshares)
        current_feed = asset.feed
        feeds = asset.feeds
        producingwitnesses = builtins.set()
        witness_accounts = [x["witness_account"] for x in witnesses]
        for feed in tqdm(feeds):
            producingwitnesses.add(feed["producer"]["id"])
            t.add_row(
                [
                    asset["symbol"],
                    feed["producer"]["name"],
                    click.style(
                        "X" if feed["producer"]["id"] in witness_accounts else "",
                        bold=True,
                    ),
                    test_date(feed["date"]),
                    test_price(
                        feed["settlement_price"], current_feed["settlement_price"]
                    ),
                    test_price(
                        feed["core_exchange_rate"], current_feed["core_exchange_rate"]
                    ),
                    feed["maintenance_collateral_ratio"] / 10,
                    feed["maximum_short_squeeze_ratio"] / 10,
                    price_diff(
                        feed["core_exchange_rate"], current_feed["core_exchange_rate"]
                    ),
                ]
            )
        for missing in builtins.set(witness_accounts).difference(producingwitnesses):
            witness = Witness(missing)
            t.add_row(
                [
                    click.style(asset["symbol"], bg="red"),
                    click.style(witness.account["name"], bg="red"),
                    click.style(
                        "X" if feed["producer"]["id"] in witness_accounts else "",
                        bold=True,
                    ),
                    click.style(str(datetime(1970, 1, 1))),
                    click.style("missing", bg="red"),
                    click.style("missing", bg="red"),
                    click.style("missing", bg="red"),
                    click.style("missing", bg="red"),
                    click.style("missing", bg="red"),
                ]
            )
        output += t.get_string(sortby="Date", reversesort=True)
        output += "\n"
    click.echo(output)
1171549
function putAsset(key, content) {
  return new Promise((resolve, reject) => {
    return instance.assets.then(db => {
      const obj = db.transaction(db.name, 'readwrite')
        .objectStore(db.name);
      const req = obj.put({key: key, value: content});
      req.onerror = event => reject(event);
      req.onsuccess = () => resolve();
    });
  });
}
40178
def fetch(cls, client, _id, symbol):
        
        url = "https://api.robinhood.com/options/chains/"
        params = {
            "equity_instrument_ids": _id,
            "state": "active",
            "tradability": "tradable"
        }
        data = client.get(url, params=params)

        def filter_func(x):
            return x["symbol"] == symbol
        results = list(filter(filter_func, data["results"]))
        return results[0]
1144624
function requireAssets( requireFile, assetPaths, assetUrlPaths ) {
   return function( assets ) {
      return Promise.all( Object.keys( assets ).map( key => {
         const asset = assets[ key ];

         if( ( assetPaths || [] ).indexOf( key ) >= 0 ) {
            return requireFile( asset, 'content' )
               .then( content => ( { [ key ]: { content } } ) );
         }

         if( ( assetUrlPaths || [] ).indexOf( key ) >= 0 ) {
            return requireFile( asset, 'url' )
               .then( url => ( { [ key ]: { url } } ) );
         }

         return {};
      } ) ).then( merge );
   };
}
1070262
def reset_assets(self, init_cash=None):
        ''
        self.sell_available = copy.deepcopy(self.init_hold)
        self.history = []
        self.init_cash = init_cash
        self.cash = [self.init_cash]
        self.cash_available = self.cash[-1]
451711
function checkStability() {
		db.query(
			"SELECT is_stable, asset, SUM(amount) AS `amount` \n\
			FROM outputs JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_spent=0 GROUP BY asset ORDER BY asset DESC LIMIT 1", 
			[addrInfo.address],
			function(rows){
				if (rows.length === 0) {
					cb("This textcoin either was already claimed or never existed in the network");
				} else {
					var row = rows[0];
					if (false && !row.is_stable) {
						cb("This payment is not confirmed yet, try again later");
					} else {
						if (row.asset) { // claiming asset
							opts.asset = row.asset;
							opts.amount = row.amount;
							opts.fee_paying_addresses = [addrInfo.address];
							storage.readAsset(db, row.asset, null, function(err, objAsset){
								if (err && err.indexOf("not found" !== -1)) {
									if (!conf.bLight) // full wallets must have this asset
										throw Error("textcoin asset "+row.asset+" not found");
									return network.requestHistoryFor([opts.asset], [], checkStability);
								}
								asset = opts.asset;
								opts.to_address = addressTo;
								if (objAsset.fixed_denominations){ // indivisible
									opts.tolerance_plus = 0;
									opts.tolerance_minus = 0;
									indivisibleAsset.composeAndSaveIndivisibleAssetPaymentJoint(opts);
								}
								else{ // divisible
									divisibleAsset.composeAndSaveDivisibleAssetPaymentJoint(opts);
								}
							});
						} else {// claiming bytes
							opts.send_all = true;
							opts.outputs = [{address: addressTo, amount: 0}];
							opts.callbacks = composer.getSavingCallbacks(opts.callbacks);
							composer.composeJoint(opts);
						}
					}
				}
			}
		);		
	}
103435
def validate(self,
                 _portfolio,
                 account,
                 algo_datetime,
                 _algo_current_data):
        
        if (algo_datetime > self.deadline and
                account.leverage < self.min_leverage):
            self.fail()
356750
def __getCashToBuyStock(self):
        '''  '''
        account=self.__strategy.getAccountCopy()
        if (account.getCash() >= account.getTotalValue() / self.buying_ratio):
            return account.getTotalValue() / self.buying_ratio
        else:
            return 0
467639
public static Wallet adaptWallet(BitMarketBalance balance) {

    List<Balance> balances = new ArrayList<>(balance.getAvailable().size());

    for (Map.Entry<String, BigDecimal> entry : balance.getAvailable().entrySet()) {
      Currency currency = Currency.getInstance(entry.getKey());
      BigDecimal frozen =
          balance.getBlocked().containsKey(entry.getKey())
              ? balance.getBlocked().get(entry.getKey())
              : new BigDecimal("0");
      BigDecimal available = entry.getValue();
      balances.add(new Balance(currency, available.add(frozen), available, frozen));
    }

    return new Wallet(balances);
  }
822111
def settle(self, settle_data = None):
        
        #print('FROM QUANTAXIS QA_ACCOUNT: account settle')
        if self.running_environment == RUNNING_ENVIRONMENT.TZERO and self.hold_available.sum(
        ) != 0:
            raise RuntimeError(
                'QAACCOUNT: 该T0账户未当日仓位,请平仓 {}'.format(
                    self.hold_available.to_dict()
                )
            )
        if self.market_type == MARKET_TYPE.FUTURE_CN:
            # 增加逐日盯市制度

            self.static_balance['frozen'].append(
                sum(
                    [
                        rx['money'] * rx['amount']
                        for var in self.frozen.values()
                        for rx in var.values()
                    ]
                )
            )

            self.static_balance['cash'].append(self.cash[-1])
            self.static_balance['hold'].append(self.hold.to_dict())
            self.static_balance['date'].append(self.date)
            """静态权益的结算

            只关心开仓价/ 不做盯市制度

            动态权益的结算需要关心

            """

            self.static_balance['static_assets'].append(
                self.static_balance['cash'][-1] +
                self.static_balance['frozen'][-1]
            )

        self.sell_available = self.hold
        self.buy_available = self.hold
        self.cash_available = self.cash[-1]
        self.datetime = '{} 09:30:00'.format(
            QA_util_get_next_day(self.date)
        ) if self.date is not None else None
15469
function getAsset(key) {
  return new Promise((resolve, reject) => {
    return instance.assets.then(db => {
      const req = db.transaction(db.name)
        .objectStore(db.name).get(key);
      req.onsuccess = event => {
        const undef = event.target.result === undefined;
        const value = undef ? undefined : event.target.result.value;
        resolve(value);
      };
      req.onerror = event => reject(event);
    });
  });
}
688331
function onAsset(output, asset) {
    var book = output.getBook();
    var options = output.getOptions();
    var bookFS = book.getContentFS();

    var outputFolder = options.get('root');
    var outputPath = path.resolve(outputFolder, asset);

    return fs.ensureFile(outputPath)
    .then(function() {
        return bookFS.readAsStream(asset)
        .then(function(stream) {
            return fs.writeStream(outputPath, stream);
        });
    })
    .thenResolve(output);
}
641700
def get_brokendate_fx_forward_rate(self, asset_manager_id,  asset_id, price_date, value_date):
        
        self.logger.info('Calculate broken date FX Forward - Asset Manager: %s - Asset (currency): %s - Price Date: %s - Value Date: %s', asset_manager_id, asset_id, price_date, value_date)
        url = '%s/brokendateforward/%s' % (self.endpoint, asset_manager_id)
        params = {'value_date': value_date, 'asset_id':asset_id, 'price_date': price_date}
        response = self.session.get(url=url, params = params)
        if response.ok:
            forward_rate = response.json()
            self.logger.info('Retrieved broken date FX forward rate %s - %s: %s', asset_id, price_date, value_date)
            return forward_rate
        else:
            self.logger.error(response.text)
            response.raise_for_status()
1164108
def _symbols2assets(self, symbols):
        '''
        
        '''

        assets = {a.symbol: a for a in self.get_equities()}
        return [assets[symbol] for symbol in symbols if symbol in assets]
946908
def __getCashToBuyStock(self):
        '''  '''
        account=self.__strategy.getAccountCopy()

        if (account.buyingPower >= account.getTotalValue() / self.__buyingRatio):
            return account.getTotalValue() / self.__buyingRatio
        else:
            return 0