Issue bid order.
 Need api key.
171691
def bid(currency_code, price, amount, limit = nil, counter_currency_code = "jpy")
            return trade(currency_code, price, amount, "bid", limit, counter_currency_code)
        end
854160
public function postBid(Request $request)
    {
        $item = Item::findOrFail($request->input('item_id'));

        if ($item->seller->userId == Auth::user()->userId) {
            return redirect()->back()->withErrors([
                'You cannot bid on your own items.',
            ]);
        }

        if (time() < $item->startDate) {
            return redirect()->back()->withErrors([
                'This item is not yet open for bidding.',
            ]);
        }

        if (time() > $item->endDate) {
            return redirect()->back()->withErrors([
                'This item has ended and cannot be bid on.',
            ]);
        }

        $minimum_bid = ($item->bids->count())
            ? BidIncrement::getMinimumNextBid($item->biddingPrice)
            : $item->startPrice;

        $highest_bid = $item->getBidHistory()->first();

        // If highest bidder, new bid must be higher than existing maximum
        if ($highest_bid && $highest_bid->bidder == Auth::user()) {
            if ($request->input('amount') < BidIncrement::getMinimumNextBid($highest_bid->amount)) {
                return redirect()->back()->withErrors([
                    'amount' => 'Your new maximum bid does not meet the minimum amount.',
                ]);
            }
        // Not highest bidder, so bid must be higher than minimum amount for current bidding price
        } elseif ($request->input('amount') < $minimum_bid) {
            return redirect()->back()->withErrors([
                'amount' => 'Your bid does not meet the minimum amount.',
            ]);
        }

        $this->validate(
            $request,
            [
                'amount' => 'required|monetary',
            ]
        );

        $item->placeBid($request->input('amount'), Auth::user());

        // If there's no highest bid, there's no bids, so bidding price can stay at start price
        if ($highest_bid) {
            // Have we beaten the highest bid?
            if ($request->input('amount') > $highest_bid->amount) {
                // If the reserve price is above the last highest bid but below the new maximum bid, set bidding to that
                if ($item->isReserved() && $request->input('amount') >= $item->reservePrice) {
                    $item->biddingPrice = $item->reservePrice;
                }

                // Check if we're increasing the maximum bid
                if ($highest_bid->bidder == Auth::user()) {
                    // Save in case the bidding price has been bumped to the reserve
                    $item->save();

                    $highest_bid->delete();

                    return redirect()->back()->withStatus('Your maximum bid has been increased.');
                }

                // Make sure we're not using the reserve price as the new bidding price
                if (!in_array('bidding_price', array_keys($item->getDirty()))) {
                    // Set bidding to the maximum bid or the next increment, whichever is lower
                    $item->biddingPrice = min([
                        $request->input('amount'),
                        // Calculate the next increment after the previous highest bid
                        $item::getMinimumBidAmount($highest_bid->amount),
                    ]);
                }

                $highest_bid->bidder->sendEmail(
                    "You've been outbid",
                    'emails.item.outbid',
                    [
                        'item_id'    => $item->itemId,
                        'item_name'  => $item->name,
                        'item_price' => $item->biddingPrice,
                    ]
                );
            // We're not the highest bid, so just increment
            } else {
                $item->biddingPrice = $request->input('amount');
            }
        } else {
            $item->biddingPrice = ($item->isReserved() && $request->input('amount') >= $item->reservePrice)
                ? $item->reservePrice
                : $item->startPrice;
        }

        $item->save();

        return redirect()->back()->withStatus('Your bid has been placed.');
    }
832991
function bidToBannerImp(bid) {
  const imp = {};

  imp.id = bid.bidId;

  imp.banner = {};
  imp.banner.w = bid.params.size[0];
  imp.banner.h = bid.params.size[1];
  imp.banner.topframe = utils.inIframe() ? 0 : 1;

  imp.ext = {};
  imp.ext.siteID = bid.params.siteId;

  if (bid.params.hasOwnProperty('id') &&
    (typeof bid.params.id === 'string' || typeof bid.params.id === 'number')) {
    imp.ext.sid = String(bid.params.id);
  } else {
    imp.ext.sid = `${bid.params.size[0]}x${bid.params.size[1]}`;
  }

  if (bid.params.hasOwnProperty('bidFloor') && bid.params.hasOwnProperty('bidFloorCur')) {
    imp.bidfloor = bid.params.bidFloor;
    imp.bidfloorcur = bid.params.bidFloorCur;
  }

  return imp;
}
791923
function(_bid){
        var _batch = _xcache[_bid];
        if (!_batch) return;
        _batch.u = _batch.u.replace(/(\?|$)/,(
                   _batch.m.callCount>1
                   ?'Multiple.'+_batch.m.callCount
                   :_batch.m['c0-scriptName']+'.'+
                    _batch.m['c0-methodName'])+'.dwr$1');
        var _option = _batch.r,
            _script = !!_option.script,
            _ispost = _option.method=='POST';
        delete _batch.r;
        delete _option.script;
        _option.method = _option.method.toUpperCase();
        _option.onerror = __onErrorWithReq._$bind(null,_bid);
        if (_script||!_ispost){
            _batch.u += (_batch.u.indexOf('?')>=0?'&':'?')
                        +__doSerializeSendData(_batch.m,'&');
        }
        if (_script){
            _j1._$loadScript(_batch.u,_option);
        }else{
            _option.onload = __onLoadWithXDR._$bind(null,_bid);
            _option.data = _ispost?__doSerializeSendData(_batch.m):null;
            _j0._$request(_batch.u,_option);
        }
    }
1354777
function(bidRequests, bidderRequest) {
    // var currency = config.getConfig(currency);

    var currentBidRequest = bidRequests[0];
    if (bidRequests.length > 1) {
      utils.logMessage('Prebid.JS - freewheel bid adapter: only one ad unit is required.');
    }

    var zone = currentBidRequest.params.zoneId;
    var timeInMillis = new Date().getTime();
    var keyCode = hashcode(zone + '' + timeInMillis);

    var requestParams = {
      reqType: 'AdsSetup',
      protocolVersion: '2.0',
      zoneId: zone,
      componentId: getComponentId(currentBidRequest.params.format),
      timestamp: timeInMillis,
      pKey: keyCode
    };

    // Add GDPR flag and consent string
    if (bidderRequest.gdprConsent) {
      requestParams._fw_gdpr_consent = bidderRequest.gdprConsent.consentString;

      if (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') {
        requestParams._fw_gdpr = bidderRequest.gdprConsent.gdprApplies;
      }
    }

    if (currentBidRequest.params.gdpr_consented_providers) {
      requestParams._fw_gdpr_consented_providers = currentBidRequest.params.gdpr_consented_providers;
    }

    var vastParams = currentBidRequest.params.vastUrlParams;
    if (typeof vastParams === 'object') {
      for (var key in vastParams) {
        if (vastParams.hasOwnProperty(key)) {
          requestParams[key] = vastParams[key];
        }
      }
    }

    var location = utils.getTopWindowUrl();
    if (isValidUrl(location)) {
      requestParams.loc = location;
    }

    var playerSize = getBiggerSize(currentBidRequest.sizes);
    if (playerSize[0] > 0 || playerSize[1] > 0) {
      requestParams.playerSize = playerSize[0] + 'x' + playerSize[1];
    }

    return {
      method: 'GET',
      url: FREEWHEEL_ADSSETUP,
      data: requestParams,
      bidRequest: currentBidRequest
    };
  }
1040812
def get_sell(self, sell_id, **params):
        """"""
        return self.api_client.get_sell(self.id, sell_id, **params)
166008
function(bid) {
    const siteId = bid.params.siteId || '';
    if (!siteId) {
      utils.logError(LOG_MSG.noSite);
    }
    return !!(bid.adUnitCode && siteId);
  }
597281
def offers
      offers = get('/api/1/BTCUSD/depth/fetch')
      asks = offers['asks'].sort_by { |ask| ask['price_int'].to_i }.collect { |ask| Ask.new(self, ask) }
      bids = offers['bids'].sort_by { |bid| -bid['price_int'].to_i }.collect { |bid| Bid.new(self, bid) }
      {:asks => asks, :bids => bids}
    end
788773
def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0):
        
        OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice
        TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC
        LimitPrice = 0.0
        VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV

        if pType == OrderType.Market:  # 市价
            OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice
            TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC
            LimitPrice = 0.0
            VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV
        elif pType == OrderType.Limit:  # 限价
            OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice
            TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD
            LimitPrice = pPrice
            VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV
        elif pType == OrderType.FAK:  # FAK
            OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice
            TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC
            LimitPrice = pPrice
            VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV
        elif pType == OrderType.FOK:  # FOK
            OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice
            TimeCondition = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC
            LimitPrice = pPrice
            VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV  # 全部数量

        self._req += 1
        self.t.ReqOrderInsert(
            BrokerID=self.broker,
            InvestorID=self.investor,
            InstrumentID=pInstrument,
            OrderRef="%06d%06d" % (self._req, pCustom % 1000000),
            UserID=self.investor,
            # 此处ctp_enum与at_struct名称冲突
            Direction=TThostFtdcDirectionType.THOST_FTDC_D_Buy if pDirection == DirectType.Buy else TThostFtdcDirectionType.THOST_FTDC_D_Sell,
            CombOffsetFlag=chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value if pOffset == OffsetType.Open else TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value if pOffset == OffsetType.CloseToday else TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value),
            CombHedgeFlag=chr(TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value),
            IsAutoSuspend=0,
            ForceCloseReason=TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose,
            IsSwapOrder=0,
            ContingentCondition=TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately,
            VolumeCondition=VolumeCondition,
            MinVolume=1,
            VolumeTotalOriginal=pVolume,
            OrderPriceType=OrderPriceType,
            TimeCondition=TimeCondition,
            LimitPrice=LimitPrice,
        )
144294
function buildRtbRequest(imps, auctionId) {
  let req = {
    'id': auctionId,
    'imp': imps,
    'site': createSite(),
    'at': 1,
    'device': {
      'ip': 'caller',
      'ua': 'caller',
      'js': 1,
      'language': getLanguage()
    },
    'ext': {
      'adk_usersync': 1
    }
  };
  if (utils.getDNT()) {
    req.device.dnt = 1;
  }
  return req;
}
588916
function (serverResponse, { bidderRequest }) {
    serverResponse = serverResponse.body;
    const bids = [];

    if (!serverResponse || serverResponse.error) {
      let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`;
      if (serverResponse && serverResponse.error) {
        errorMessage += `: ${serverResponse.error}`;
        utils.logError(errorMessage);
      }
      return bids;
    }

    if (!utils.isArray(serverResponse.seatbid)) {
      let errorMessage = `in response for ${bidderRequest.bidderCode} adapter `;
      utils.logError(errorMessage += 'Malformed seatbid response');
      return bids;
    }

    if (!serverResponse.seatbid) {
      return bids;
    }

    const currency = serverResponse.cur || DEFAULT_CURRENCY;
    serverResponse.seatbid.forEach(sBid => {
      if (sBid.hasOwnProperty('bid')) {
        sBid.bid.forEach(iBid => {
          if (iBid.price !== 0) {
            const bid = newBid(iBid, currency);
            bids.push(bid);
          }
        });
      }
    });
    return bids;
  }
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
525416
function(serverResponse) {
    serverResponse = serverResponse.body;

    const bids = [];

    if (serverResponse.id) {
      const bid = newBid(serverResponse);
      bids.push(bid);
    }

    return bids;
  }
1118057
def key_from_req(req):
    """"""
    if hasattr(req, "key"):
        # from pkg_resources, such as installed dists for pip-sync
        key = req.key
    else:
        # from packaging, such as install requirements from requirements.txt
        key = req.name

    key = key.replace("_", "-").lower()
    return key
327651
async def post(self, public_key):
		
		logging.debug("[+] -- Deal debugging. ")
		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
		logging.debug("\n         Body")
		logging.debug(body)
			
		if isinstance(body["message"], str):
			message = json.loads(body["message"])
		elif isinstance(body["message"], dict):
			message = body["message"]

		cid = message.get("cid")
		buyer_pubkey = message.get("buyer_pubkey")
		buyer_access_string = message.get("buyer_access_string")

		seller_access_string = message.get("seller_access_string")
		access_type = message.get("access_type")

		coinid = message.get("coinid")
		# check passes data
		if not all([buyer_access_string, cid, buyer_pubkey, 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 

		# Sellcontent
		buyer_address = self.account.validator[coinid](buyer_pubkey)

		# Check if accounts exists
		seller_account = await self.account.getaccountdata(public_key=public_key)
		logging.debug("\n          Seller account")
		logging.debug(seller_account)

		try:
			error_code = seller_account["error"]
		except:
			pass
		else:
			self.set_status(error_code)
			self.write(seller_account)
			raise tornado.web.Finish

		buyer_account = await self.account.getaccountdata(public_key=buyer_pubkey)
		logging.debug("\n           Buyer account")
		logging.debug(buyer_account)
		try:
			error_code = buyer_account["error"]
		except:
			pass
		else:
			self.set_status(error_code)
			self.write(buyer_account)
			raise tornado.web.Finish

		# Check if content belongs to current account
		owneraddr = await self.account.blockchain.ownerbycid(cid=cid)
		
		
		if owneraddr != self.account.validator[coinid](public_key):
			self.set_status(403)
			self.write({"error":403, "reason":"Forbidden. Profile owner does not match."})
			raise tornado.web.Finish

		#Get buyers balance
		balances = await self.account.balance.get_wallets(coinid=coinid, 
														uid=buyer_account["id"])
		if isinstance(balances, dict):
			if "error" in balances.keys():
				self.set_status(balances["error"])
				self.write(balances)
				raise tornado.web.Finish 


		# Get difference with balance and price
		get_price = await self.account.blockchain.getoffer(buyer_address=buyer_address,
															cid=cid)
		price = get_price["price"]
		logging.debug("\n          Price")
		logging.debug(price)

		for w in balances["wallets"]:
			if "PUT" in w.values() or "PUTTEST" in w.values():
				balance = w

		difference = int(balance["amount_frozen"]) - int(price)

		if difference >= 0:

			if access_type == "write_access":
				logging.debug("\n          Write access")
				# Fee
				fee = await billing.change_owner_fee(cid=cid, new_owner=buyer_pubkey)
				if "error" in fee.keys():
					self.set_status(fee["error"])
					self.write(fee)
					raise tornado.web.Finish
			
				# Change content owner
				chownerdata = {
					"cid":cid,
					"new_owner": buyer_address,
					"access_string": buyer_access_string,
					"seller_public_key": public_key
				}

				response = await self.account.blockchain.changeowner(**chownerdata)
				logging.debug("\n         Bridge change owner")
				logging.debug(response)

				new_owner = await self.account.changeowner(cid=cid, 
										public_key=buyer_account["public_key"], 
										coinid=coinid)
				logging.debug("\n Database new owner")
				logging.debug(new_owner)

			elif access_type == "read_access":
				logging.debug("\n          Read access")

				# Fee
				fee = await billing.sell_content_fee(cid=cid, new_owner=buyer_pubkey)

				if "error" in fee.keys():
					self.set_status(fee["error"])
					self.write(fee)
					raise tornado.web.Finish

				selldata = {
					"cid":cid,
					"buyer_address":buyer_address,
					"access_string":buyer_access_string,
					"seller_public_key":public_key
				}

				response = await self.account.blockchain.sellcontent(**selldata)
				logging.debug("\n        Bridge sell content")

				# Write cid to database
				check = await self.account.setuserscontent(public_key=buyer_account["public_key"], 
											hash=None,coinid=coinid, cid=cid,
											txid=response["result"]["txid"],
											access="deal")
				logging.debug(check)

			
			# Increment and decrement balances of seller and buyer
			coinid = "PUT"
			unfreeze = await self.account.balance.unfreeze(uid=buyer_account["id"],
													amount=price, coinid=coinid)
			logging.debug("\n          Unfreeze buyer")
			logging.debug(unfreeze)

			sub_active = await self.account.balance.sub_active(uid=buyer_account["id"], 
												coinid=coinid, amount=price)
			logging.debug("\n            Sub active")
			logging.debug(sub_active)
			add_frozen = await self.account.balance.add_frozen(uid=seller_account["id"], 
												amount=price, coinid=coinid)
			logging.debug("\n               Add frozen")
			logging.debug(add_frozen)
			# Write entry with txid to database
			new_deal = await self.account.balance.registerdeal(uid=seller_account["id"],
													public_key=seller_account["public_key"], 
													txid=response["result"]["txid"],
													coinid=coinid, cid=cid)

			del response["result"]
			del response["contract_owner_hex"]
			self.write(response)
		else:
			# If Insufficient funds
			self.set_status(402)
			self.write({"error":402, "reason":"Insufficient funds of buyer"})
			raise tornado.web.Finish
1055379
function (bid) {
    return !!(bid && bid.params && bid.params.adCode && bid.params.supplyCode);
  }
152586
def send_margin_order(self, acc_id, amount, symbol, _type, price=0, _async=False):
        

        params = {
            'account-id': acc_id,
            'amount': amount,
            'symbol': symbol,
            'type': _type,
            'source': 'margin-api'
        }
        if price:
            params['price'] = price

        path = '/v1/order/orders/place'
        return api_key_post(params, path, _async=_async)