Register to streaming market data updates
        https://www.interactivebrokers.com/en/software/api/apiguide/java/reqmktdata.htm
351855
def requestMarketData(self, contracts=None, snapshot=False):
        
        if contracts == None:
            contracts = list(self.contracts.values())
        elif not isinstance(contracts, list):
            contracts = [contracts]

        for contract in contracts:
            if snapshot:
                reqType = ""
            else:
                reqType = dataTypes["GENERIC_TICKS_RTVOLUME"]
                if contract.m_secType in ("OPT", "FOP"):
                    reqType = dataTypes["GENERIC_TICKS_NONE"]

            # get market data for single contract
            # limit is 250 requests/second
            if not self.isMultiContract(contract):
                try:
                    tickerId = self.tickerId(self.contractString(contract))
                    self.ibConn.reqMktData(tickerId, contract, reqType, snapshot)
                    time.sleep(0.0042)  # 250 = 1.05s
                except KeyboardInterrupt:
                    sys.exit()
597156
public static Map<String, String> AppConsumeByMap(Map<String, String> reqData) {
		return SDKUtil.convertResultStringToMap(AppConsume(reqData));
	}
1051122
private void registerJMXStuff() {
    LOG.info("registering InApplicationMonitorDynamicMBean on JMX server");

    try {
      jmxBeanRegistrationHelper.registerMBeanOnJMX(this, "InApplicationMonitor", null);
    } catch (Exception e) {
      LOG.error("could not register MBean server : ", e);
    }
  }
575132
def load_data(self):
        
        try:
            df = self.live_quote_arg_func(self.tickers)
            for index, ticker in enumerate(self.tickers):
                ticker_info = df.loc[index]
                self.ticker_dict[ticker].append(ticker_info['price'],
                                                ticker_info['volume'],
                                                ticker_info['amount'],
                                                ticker_info['time'])
        except Exception:
            raise ValueError('Polling thread exception')
929073
function getMarketCaps() {

    return new Promise(function (resolve, reject) {

        scraper
            .get(urlMarketCap)
            .then(function(tableData) {
                const coinmarketcapTable = tableData[0];
                resolve(getAllMarketCaps(coinmarketcapTable));
            });
    });
}
1333707
function connect() {
  console.log('Connecting client: ' + clientId + ' to url:"' + url + '"');
  client = mqtt.connect(url, { 'clientId': clientId });
}
755067
def update_orders(self, market_id, instructions, customer_ref=None):
        
        return self.make_api_request(
            'Sports',
            'updateOrders',
            utils.get_kwargs(locals()),
            model=models.UpdateExecutionReport,
        )
1253860
def query(self, out_trade_no, bill_type='MCHT'):
        
        data = {
            'mch_billno': out_trade_no,
            'bill_type': bill_type,
            'appid': self.appid,
        }
        return self._post('mmpaymkttransfers/gethbinfo', data=data)
839433
def update_data(new_data = nil)
      new_data ||= JSON.parse(API::Server.resolve(@bot.token, @id))
      @name = new_data[:name] || new_data['name'] || @name
      @region_id = new_data[:region] || new_data['region'] || @region_id
      @icon_id = new_data[:icon] || new_data['icon'] || @icon_id
      @afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'] || @afk_timeout

      afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'] || @afk_channel
      @afk_channel_id = afk_channel_id.nil? ? nil : afk_channel_id.resolve_id
      embed_channel_id = new_data[:embed_channel_id] || new_data['embed_channel_id'] || @embed_channel
      @embed_channel_id = embed_channel_id.nil? ? nil : embed_channel_id.resolve_id
      system_channel_id = new_data[:system_channel_id] || new_data['system_channel_id'] || @system_channel
      @system_channel_id = system_channel_id.nil? ? nil : system_channel_id.resolve_id

      @embed_enabled = new_data[:embed_enabled] || new_data['embed_enabled']
      @splash = new_data[:splash_id] || new_data['splash_id'] || @splash_id

      @verification_level = new_data[:verification_level] || new_data['verification_level'] || @verification_level
      @explicit_content_filter = new_data[:explicit_content_filter] || new_data['explicit_content_filter'] || @explicit_content_filter
      @default_message_notifications = new_data[:default_message_notifications] || new_data['default_message_notifications'] || @default_message_notifications
    end
299482
def run(self):
        

        # -----------------------------------
        # assign view
        app.add_url_rule('/', 'index', view_func=self.index)
        app.add_url_rule('/<path:start>', 'index', view_func=self.index)
        app.add_url_rule('/<start>/<path:end>', 'index', view_func=self.index)

        app.add_url_rule('/algos', 'algos', view_func=self.algos)
        app.add_url_rule('/symbols', 'symbols', view_func=self.symbols)

        app.add_url_rule('/positions', 'positions', view_func=self.positions)
        app.add_url_rule('/positions/<path:algo_id>',
                         'positions', view_func=self.positions)

        app.add_url_rule('/algo/<path:algo_id>',
                         'trades_by_algo', view_func=self.trades_by_algo)
        app.add_url_rule('/algo/<algo_id>/<path:start>',
                         'trades_by_algo', view_func=self.trades_by_algo)
        app.add_url_rule('/algo/<algo_id>/<start>/<path:end>',
                         'trades_by_algo', view_func=self.trades_by_algo)

        app.add_url_rule('/bars/<resolution>/<symbol>',
                         'bars', view_func=self.bars)
        app.add_url_rule(
            '/bars/<resolution>/<symbol>/<path:start>', 'bars', view_func=self.bars)
        app.add_url_rule('/bars/<resolution>/<symbol>/<start>/<path:end>',
                         'bars', view_func=self.bars)

        app.add_url_rule('/trades', 'trades', view_func=self.trades)
        app.add_url_rule('/trades/<path:start>',
                         'trades', view_func=self.trades)
        app.add_url_rule('/trades/<start>/<path:end>',
                         'trades', view_func=self.trades)
        app.add_url_rule('/login/<password>', 'login', view_func=self.login)
        app.add_url_rule('/static/<url_path>', 'send_static',
                         view_func=self.send_static)

        # let user know what the temp password is
        if 'nopass' not in self.args and self._password != "":
            print(" * Web app password is:", self._password)

        # notice
        # print(" * Running on http://"+ str(self.host) +":"+str(self.port)+"/ (CTRL+C to quit)")

        # -----------------------------------
        # run flask app
        app.run(
            debug=True,
            host=str(self.host),
            port=int(self.port)
        )
1169419
def _register_update(self, method='isel', replot=False, dims={}, fmt={},
                         force=False, todefault=False):
        
        ArrayList._register_update(self, method=method, dims=dims)
        InteractiveBase._register_update(self, fmt=fmt, todefault=todefault,
                                         replot=bool(dims) or replot,
                                         force=force)
878518
async def post(self, public_key=None):
		
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		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 = message.get("cid")
		read_price = message.get("price")
		coinid = message.get("coinid")
		buyer_access_string = message.get("buyer_access_string")
	
		if not all([buyer_access_string, coinid, str(cid).isdigit()]):
			self.set_status(400)
			self.write({"error":400, "reason":"Missed required fields"})
			raise tornado.web.Finish

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

		# Get cid price from bridge
		if not read_price:
			read_price = await self.account.blockchain.getreadprice(cid=cid)

		buyer_address = self.account.validator[coinid](public_key)
		owneraddr = await self.account.blockchain.ownerbycid(cid=cid)

		# Check if public key exists
		account = await self.account.getaccountdata(public_key=public_key)
		if "error" in account.keys():
			# If account does not exist
			self.set_status(account["error"])
			self.write(account)
			raise tornado.web.Finish

		#Get sellers balance
		balances = await self.account.balance.get_wallets(coinid=coinid, uid=account["id"])

		# Check if current content does not belong to current user
		if owneraddr == buyer_address:
			self.set_status(400)
			self.write({"error":400, 
						"reason":"Content belongs to current user"})
			raise tornado.web.Finish

		# Get difference with balance and price
		for w in balances["wallets"]:
			if "PUT" in w.values() or "PUTTEST" in w.values():
				balance = w

		difference = int(balance["amount_active"]) - int(read_price)
		if difference < 0:
			# If Insufficient funds
			self.set_status(402)
			self.write({"error":402, "reason":"Balance is not enough"})
			raise tornado.web.Finish

		# Send request to bridge
		offer_data = {
			"cid":cid,
			"read_price":read_price,
			"offer_type":0,
			"buyer_address": buyer_address,
			"buyer_access_string":buyer_access_string
		}
		response = await self.account.blockchain.makeoffer(**offer_data)
		try:
			response["error"]
		except:
			pass
		else:
			self.set_status(response["error"])
			self.write(response)
			raise tornado.web.Finish

		await self.account.insertoffer(cid=cid, txid=response["result"]["txid"], 
											coinid=coinid, public_key=public_key)
		# Send e-mail to seller
		seller = await self.account.getaccountbywallet(wallet=owneraddr)
		if "error" in seller.keys():
			self.set_status(seller["error"])
			self.write(seller)
			raise tornado.web.Finish

		if seller.get("email"):
			emaildata = {
				"to": seller["email"],
				"subject": "Robin8 support",
     			"optional": "You`ve got an offer for content %s." % cid
			}
			await self.account.mailer.sendmail(**emaildata)


		# Freeze price at balance
		coinid = "PUT"
		await self.account.balance.freeze(uid=account["id"],coinid=coinid, 
																amount=read_price)

		# Set fee
		fee = await billing.set_make_offer_fee(buyer_address=buyer_address)
		if "error" in fee.keys():
			self.set_status(fee["error"])
			self.write(fee)
			raise tornado.web.Finish

		response["offer_type"] = "read_access"
		del response["result"]		

		self.write(response)
640774
def register(self):
        """"""
        # connect to tracker
        result = requests.post(urljoin(self.tracker, 'models'), data=json.dumps(self.metadata))
        logger.debug("registered at server %s: %s", self.tracker, result)
        self.metadata["tracker"] = result.json()
1072774
public void apply()
    {
        String in = readLineWithMessage("Edit Product with id:");
        int id = Integer.parseInt(in);

        // We don't have a reference to the selected Product.
        // So first we have to lookup the object,
        // we do this by a query by example (QBE):
        // 1. build an example object with matching primary key values:
        Product example = new Product();
        example.setId(id);

        // 2. build a QueryByIdentity from this sample instance:
        Query query = new QueryByIdentity(example);
        try
        {
            // 3. start broker transaction
            broker.beginTransaction();

            // 4. lookup the product specified by the QBE
            Product toBeEdited = (Product) broker.getObjectByQuery(query);

            // 5. edit the existing entry
            System.out.println("please edit the product entry");
            in = readLineWithMessage("enter name (was " + toBeEdited.getName() + "):");
            toBeEdited.setName(in);
            in = readLineWithMessage("enter price (was " + toBeEdited.getPrice() + "):");
            toBeEdited.setPrice(Double.parseDouble(in));
            in = readLineWithMessage("enter available stock (was " + toBeEdited.getStock() + "):");
            toBeEdited.setStock(Integer.parseInt(in));



            // 6. now ask broker to store the edited object
            broker.store(toBeEdited);
            // 7. commit transaction
            broker.commitTransaction();
        }
        catch (Throwable t)
        {
            // rollback in case of errors
            broker.abortTransaction();
            t.printStackTrace();
        }
    }
1001648
@Override
  public final void process(final Map<String, Object> pRqVs,
    final IRequestData pRqDt) throws Exception {
    OnlineBuyer buyer = this.buySr.getAuthBuyr(pRqVs, pRqDt);
    if (buyer == null) {
      String procNm = pRqDt.getParameter("nmPrcRed");
      IProcessor proc = this.procFac.lazyGet(pRqVs, procNm);
      proc.process(pRqVs, pRqDt);
      return;
    }
    SettingsAdd setAdd = (SettingsAdd) pRqVs.get("setAdd");
    String purIdStr = pRqDt.getParameter("pur");
    Long.parseLong(purIdStr);
    try {
      this.srvDb.setIsAutocommit(false);
      this.srvDb.setTransactionIsolation(setAdd.getBkTr());
      this.srvDb.beginTransaction();
      String tbn = CustOrder.class.getSimpleName();
      String whePuBr = "where PUR=" + purIdStr + " and BUYER="
        + buyer.getItsId();
      Set<String> ndFlNm = new HashSet<String>();
      ndFlNm.add("itsId");
      ndFlNm.add("itsName");
      pRqVs.put("PickUpPlaceneededFields", ndFlNm);
      pRqVs.put(tbn + "buyerdeepLevel", 1);
      List<CustOrder> ords = this.srvOrm.retrieveListWithConditions(pRqVs,
        CustOrder.class, whePuBr);
      pRqVs.remove(tbn + "buyerdeepLevel");
      tbn = CuOrSe.class.getSimpleName();
      Set<String> ndFlDc = new HashSet<String>();
      ndFlDc.add("seller");
      pRqVs.put("DebtorCreditorneededFields", ndFlNm);
      pRqVs.put("SeSellerneededFields", ndFlDc);
      pRqVs.put(tbn + "seldeepLevel", 3);
      pRqVs.put(tbn + "buyerdeepLevel", 1);
      List<CuOrSe> sords = this.srvOrm.retrieveListWithConditions(pRqVs,
        CuOrSe.class, whePuBr);
      pRqVs.remove(tbn + "buyerdeepLevel");
      pRqVs.remove("DebtorCreditorneededFields");
      pRqVs.remove("SeSellerneededFields");
      pRqVs.remove(tbn + "seldeepLevel");
      pRqVs.remove("PickUpPlaceneededFields");
      retLines(pRqVs, buyer, ords, sords);
      Purch pur = new Purch();
      pur.setOrds(ords);
      pur.setSords(sords);
      pRqDt.setAttribute("pur",  pur);
      this.srvDb.commitTransaction();
    } catch (Exception ex) {
      if (!this.srvDb.getIsAutocommit()) {
        this.srvDb.rollBackTransaction();
      }
      throw ex;
    } finally {
      this.srvDb.releaseResources();
    }
  }
586834
def submit(cls, client, direction, legs, price, quantity, time_in_force,
               trigger, order_type, run_validations=True):
        '''
        
        '''

        if run_validations:
            assert(direction in ["debit", "credit"])
            assert(type(price) is str)
            assert(type(quantity) is int)
            assert(time_in_force in ["gfd", "gtc"])
            assert(trigger in ["immediate"])
            assert(order_type in ["limit", "market"])
            assert(cls._validate_legs(legs) is True)

        payload = json.dumps({
            "account": client.account_url,
            "direction": direction,
            "legs": legs,
            "price": price,
            "quantity": quantity,
            "time_in_force": time_in_force,
            "trigger": trigger,
            "type": order_type,
            "override_day_trade_checks": False,
            "override_dtbp_checks": False,
            "ref_id": str(uuid.uuid4())
        })

        request_url = "https://api.robinhood.com/options/orders/"
        data = client.post(request_url, payload=payload)
        return data
845929
function register(app, targetEndpoint) {
  var builder = new Builder(app, targetEndpoint);

  // create and update APIs
  app.put('/apiql/apis/:name', bodyParsers(), function (req, res, done) {
    builder.buildAPI(req.params.name, req.headers['content-type'], req.body, function (err) {
      if (err) {
        res.sendStatus(400);
      } else {
        res.sendStatus(204);
      }
      done();
    });
  });

  app.get('/apiql/apis', function (req, res, done) {
    API.listAPIs(function (err, apis) {
      if (err) {
        console.log(err);
      }
      res.format({
        json: function () {
          res.json({ items: _.map(apis, (api) => api.toJson()) }); // returns empty array even with error
        },
        default: function () {
          res.sendStatus(406);
        }
      });
      done();
    });
  });

  app.get('/apiql/apis/:name', function (req, res, done) {
    API.findByName(req.params.name, function (err, api) {
      if (err) {
        res.sendStatus(404);
      } else {
        res.format({
          html: function () {
            res.send(docs({ name: req.params.name, description: api.description }));
          },
          json: function () {
            res.json(api.toJson());
          },
          'application/openapi+json': function () {
            res.json(api.formattedDescription(OPENAPI_JSON));
          },
          'application/openapi+yaml': function () {
            res.send(api.formattedDescription(OPENAPI_YAML));
          },
          default: function () {
            res.sendStatus(406);
          }
        });
      }
      done();
    });
  });

  app.delete('/apiql/apis/:name', function (req, res, done) {
    builder.removeExistingAPI(req.params.name)(function (err) {
      if (err) {
        if (err.message == NOT_FOUND) {
          res.sendStatus(404);
        } else {
          res.status(500).send(err.message);
        }
      } else {
        res.sendStatus(204); // return the deleted item
      }
      done();
    });
  });

  // returns apiql OpenApi 3.0 API Description document or rendered documentation via conneg
  app.get('/apiql/api-description', function (req, res, done) {
    var description;

    try {
      description = yaml.safeLoad(fs.readFileSync(descriptionFilePath, 'utf8'));
    } catch (err) {
      console.log(err);
      res.status(500).send(err.message);
    }

    res.format({
      html: function () {
        res.send(docs({ name: 'APIQL Docs', description: description }));
      },
      'application/openapi+json': function () {
        res.send(description);
      },
      'application/openapi+yaml': function () {
        res.send(yaml.safeDump(description));
      },
      default: function () {
        res.sendStatus(406);
      }
    });
    done();
  });
}