企业付款查询接口

        :param out_trade_no: 商户调用企业付款API时使用的商户订单号
        :return: 返回的结果数据
432738
def query_bankcard(self, out_trade_no):
        
        data = {
            'mch_id': self.mch_id,
            'partner_trade_no': out_trade_no,
        }
        return self._post('mmpaysptrans/query_bank', data=data)
262599
def QA_fetch_get_option_50etf_contract_time_to_market():
    '''
        
        '''
    result = QA_fetch_get_option_list('tdx')
    # pprint.pprint(result)
    #  category  market code name desc  code
    '''
    fix here : 
    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
    result['meaningful_name'] = None
    C:\work_new\QUANTAXIS\QUANTAXIS\QAFetch\QATdx.py:1468: SettingWithCopyWarning: 
    A value is trying to be set on a copy of a slice from a DataFrame.
    Try using .loc[row_indexer,col_indexer] = value instead
    '''
    # df = pd.DataFrame()
    rows = []

    result['meaningful_name'] = None
    for idx in result.index:
        # pprint.pprint((idx))
        strCategory = result.loc[idx, "category"]
        strMarket = result.loc[idx, "market"]
        strCode = result.loc[idx, "code"]  # 10001215
        strName = result.loc[idx, 'name']  # 510050C9M03200
        strDesc = result.loc[idx, 'desc']  # 10001215

        if strName.startswith("510050"):
            # print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, )

            if strName.startswith("510050C"):
                putcall = '50ETF,认购期权'
            elif strName.startswith("510050P"):
                putcall = '50ETF,认沽期权'
            else:
                putcall = "Unkown code name ： " + strName

            expireMonth = strName[7:8]
            if expireMonth == 'A':
                expireMonth = "10月"
            elif expireMonth == 'B':
                expireMonth = "11月"
            elif expireMonth == 'C':
                expireMonth = "12月"
            else:
                expireMonth = expireMonth + '月'

            # 第12位期初设为“M”，并根据合约调整次数按照“A”至“Z”依序变更，如变更为“A”表示期权合约发生首次调整，变更为“B”表示期权合约发生第二次调整，依此类推；
            # fix here : M ??
            if strName[8:9] == "M":
                adjust = "未调整"
            elif strName[8:9] == 'A':
                adjust = " 第1次调整"
            elif strName[8:9] == 'B':
                adjust = " 第2调整"
            elif strName[8:9] == 'C':
                adjust = " 第3次调整"
            elif strName[8:9] == 'D':
                adjust = " 第4次调整"
            elif strName[8:9] == 'E':
                adjust = " 第5次调整"
            elif strName[8:9] == 'F':
                adjust = " 第6次调整"
            elif strName[8:9] == 'G':
                adjust = " 第7次调整"
            elif strName[8:9] == 'H':
                adjust = " 第8次调整"
            elif strName[8:9] == 'I':
                adjust = " 第9次调整"
            elif strName[8:9] == 'J':
                adjust = " 第10次调整"
            else:
                adjust = " 第10次以上的调整，调整代码 %s" + strName[8:9]

            executePrice = strName[9:]
            result.loc[idx, 'meaningful_name'] = '%s,到期月份:%s,%s,行权价:%s' % (
                putcall, expireMonth, adjust, executePrice)

            row = result.loc[idx]
            rows.append(row)
    return rows
1104610
def get_mainmarket_ip(ip, port):
    

    global best_ip
    if ip is None and port is None and best_ip['stock']['ip'] is None and best_ip['stock']['port'] is None:
        best_ip = select_best_ip()
        ip = best_ip['stock']['ip']
        port = best_ip['stock']['port']
    elif ip is None and port is None and best_ip['stock']['ip'] is not None and best_ip['stock']['port'] is not None:
        ip = best_ip['stock']['ip']
        port = best_ip['stock']['port']
    else:
        pass
    return ip, port
753133
public function sendPayDeliverNotify($openid,$transid,$out_trade_no,$status=1,$msg='ok'){
		if (!$this->access_token && !$this->checkAuth()) return false;
		$postdata = array(
				"appid"=>$this->appid,
				"appkey"=>$this->paysignkey,
				"openid"=>$openid,
				"transid"=>strval($transid),
				"out_trade_no"=>strval($out_trade_no),
				"deliver_timestamp"=>strval(time()),
				"deliver_status"=>strval($status),
				"deliver_msg"=>$msg,
		);
		$postdata['app_signature'] = $this->getSignature($postdata);
		$postdata['sign_method'] = 'sha1';
		unset($postdata['appkey']);
		$result = $this->http_post(self::API_BASE_URL_PREFIX.self::PAY_DELIVERNOTIFY.'access_token='.$this->access_token,self::json_encode($postdata));
		if ($result)
		{
			$json = json_decode($result,true);
			if (!$json || !empty($json['errcode'])) {
				$this->errCode = $json['errcode'];
				$this->errMsg = $json['errmsg'];
				return false;
			}
			return $json;
		}
		return false;
	}
306469
def _execute_trade_cmd(
        self, trade_cmd, users, expire_seconds, entrust_prop, send_interval
    ):
        
        for user in users:
            # check expire
            now = datetime.datetime.now()
            expire = (now - trade_cmd["datetime"]).total_seconds()
            if expire > expire_seconds:
                log.warning(
                    "策略 [%s] 指令(股票: %s 动作: %s 数量: %s 价格: %s)超时，指令产生时间: %s 当前时间: %s, 超过设置的最大过期时间 %s 秒, 被丢弃",
                    trade_cmd["strategy_name"],
                    trade_cmd["stock_code"],
                    trade_cmd["action"],
                    trade_cmd["amount"],
                    trade_cmd["price"],
                    trade_cmd["datetime"],
                    now,
                    expire_seconds,
                )
                break

            # check price
            price = trade_cmd["price"]
            if not self._is_number(price) or price <= 0:
                log.warning(
                    "策略 [%s] 指令(股票: %s 动作: %s 数量: %s 价格: %s)超时，指令产生时间: %s 当前时间: %s, 价格无效 , 被丢弃",
                    trade_cmd["strategy_name"],
                    trade_cmd["stock_code"],
                    trade_cmd["action"],
                    trade_cmd["amount"],
                    trade_cmd["price"],
                    trade_cmd["datetime"],
                    now,
                )
                break

            # check amount
            if trade_cmd["amount"] <= 0:
                log.warning(
                    "策略 [%s] 指令(股票: %s 动作: %s 数量: %s 价格: %s)超时，指令产生时间: %s 当前时间: %s, 买入股数无效 , 被丢弃",
                    trade_cmd["strategy_name"],
                    trade_cmd["stock_code"],
                    trade_cmd["action"],
                    trade_cmd["amount"],
                    trade_cmd["price"],
                    trade_cmd["datetime"],
                    now,
                )
                break

            actual_price = self._calculate_price_by_slippage(
                trade_cmd["action"], trade_cmd["price"]
            )
            args = {
                "security": trade_cmd["stock_code"],
                "price": actual_price,
                "amount": trade_cmd["amount"],
                "entrust_prop": entrust_prop,
            }
            try:
                response = getattr(user, trade_cmd["action"])(**args)
            except exceptions.TradeError as e:
                trader_name = type(user).__name__
                err_msg = "{}: {}".format(type(e).__name__, e.args)
                log.error(
                    "%s 执行 策略 [%s] 指令(股票: %s 动作: %s 数量: %s 价格(考虑滑点): %s 指令产生时间: %s) 失败, 错误信息: %s",
                    trader_name,
                    trade_cmd["strategy_name"],
                    trade_cmd["stock_code"],
                    trade_cmd["action"],
                    trade_cmd["amount"],
                    actual_price,
                    trade_cmd["datetime"],
                    err_msg,
                )
            else:
                log.info(
                    "策略 [%s] 指令(股票: %s 动作: %s 数量: %s 价格(考虑滑点): %s 指令产生时间: %s) 执行成功, 返回: %s",
                    trade_cmd["strategy_name"],
                    trade_cmd["stock_code"],
                    trade_cmd["action"],
                    trade_cmd["amount"],
                    actual_price,
                    trade_cmd["datetime"],
                    response,
                )
1092195
def trade(args):
    """"""
    print args
    print vars(args)['funds']
    print args.funds
    portfolio = { '$CASH': args.funds }
    print portfolio
    csvreader = csv.reader(args.infile, dialect='excel', quoting=csv.QUOTE_MINIMAL)
    csvwriter = csv.writer(args.outfile, dialect='excel', quoting=csv.QUOTE_MINIMAL)
    detailed = not args.simple
    history = []
    portfolio_history = []

    #trading_days = du.getNYSEdays(datetime.datetime(2010,01,01), datetime.datetime(2012,01,01), datetime.timedelta(hours=16))
    for row in csvreader:
        # print '-'*30 + ' CSV Row ' + '-'*30
        # print ', '.join(row)
        trade_date = datetime.datetime(*[int(i) for i in (row[:3] + [16])])

        if history:
            last_date = datetime.datetime(*(history[-1][:3] + [16])) + datetime.timedelta(days=1)
            # print (date.date() - last_date).days
            while (trade_date - last_date).days > 0:
                print 'Filling in the blanks for {0}'.format(last_date)
                value = portfolio_value(portfolio, last_date, price='close')
                print '   the portfolio value on that date is: {0}'.format(value)
                assert(value != None)
                # NaN for porfolio value indicates a non-trading day
                if not np.isnan(value):
                    history += [[last_date.year, last_date.month, last_date.day] 
                                + (["$CASH", "0.0", "0.0"] if args.trades else [])
                                + ([json.dumps(portfolio)] if detailed else []) + [value]]
                    portfolio_history += [datetime.datetime(last_date.year, last_date.month, last_date.day, 16), portfolio]
                    csvwriter.writerow(history[-1])
                last_date += datetime.timedelta(days=1)
    
        trade_symbol = row[3]
        trade_shares = float(row[5])
        trade_sign = 1 - 2 * int(row[4].strip().upper()[0]=='S')
        # If this the first row in the CSV and the symbol is $CASH then it represents an initial deposit (Sell) or withdrawal (Buy) of cash
        # otherwise se need to add or deduct whatever security was bought or sold.
        # if not (trade_symbol == '$CASH') or history:
        portfolio[trade_symbol] = portfolio.get(trade_symbol, 0) + trade_sign * trade_shares
        trade_price = get_price(symbol=trade_symbol, date=trade_date, price='close')
        while trade_price == None or np.isnan(trade_price) or float(trade_price) == float('nan'):
            trade_date += datetime.timedelta(days=1)
            trade_price = get_price(symbol=trade_symbol, date=trade_date, price='close')
        #print trade_date, trade_symbol, trade_sign, trade_shares, trade_price
        if trade_price and trade_shares and trade_sign in (-1, 1):
            print 'spending cash: {0}'.format(trade_sign * trade_shares * trade_price)
            portfolio['$CASH'] = portfolio.get('$CASH',0.) - trade_sign * trade_shares * trade_price
        else:
            print 'ERROR: bad price, sign, shares: ', trade_price, trade_sign, trade_shares
        history += [[trade_date.year, trade_date.month, trade_date.day, trade_symbol, trade_sign, trade_shares] + ([json.dumps(portfolio)] if detailed else []) + [portfolio_value(portfolio, trade_date, price='close')]]
        csvwriter.writerow(history[-1])
    return metrics(history)
505888
public RefundQuery refundQueryByTradeNumber(String tradeNumber) {
        RefundQueryRequestWrapper refundQueryRequestWrapper = new RefundQueryRequestWrapper();
        refundQueryRequestWrapper.setTradeNumber(tradeNumber);
        return refundQuery(refundQueryRequestWrapper);
    }
1340375
def trading_fees(self) -> TradingFees:
        """"""
        return self._fetch('trading fees', self.market.code)(self._trading_fees)()
688446
public void getTradesWithOrderId(KiteConnect kiteConnect) throws KiteException, IOException {
        // Returns trades for the given order.
        List<Trade> trades = kiteConnect.getOrderTrades("180111000561605");
        System.out.println(trades.size());
    }
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]
189845
def _get_benchmark_handler(self, last_trade, freq='minutely'):
        '''
        
        '''
        return LiveBenchmark(
            last_trade, frequency=freq).surcharge_market_data \
            if utils.is_live(last_trade) else None
1238555
def unspent_outputs(self):
        
        if self.operation == Transaction.CREATE:
            self._asset_id = self._id
        elif self.operation == Transaction.TRANSFER:
            self._asset_id = self.asset['id']
        return (UnspentOutput(
            transaction_id=self._id,
            output_index=output_index,
            amount=output.amount,
            asset_id=self._asset_id,
            condition_uri=output.fulfillment.condition_uri,
        ) for output_index, output in enumerate(self.outputs))
1245844
public WePayOrder queryByOutTradeNo(String outTradeNo){
        checkNotNullAndEmpty(outTradeNo, "outTradeNo");
        Map<String, String> queryParams = new TreeMap<>();
        put(queryParams, WepayField.OUT_TRADE_NO, outTradeNo);
        return doQueryOrder(queryParams);
    }
821358
def tradevolume(self):
        """"""
        request = '/v1/tradevolume'
        url = self.base_url + request
        params = {
            'request': request,
            'nonce': self.get_nonce()
        }

        return requests.post(url, headers=self.prepare(params))
453393
def send(self, user_id, stock_id, op_user_id=None, device_info=None,
             out_trade_no=None):
        
        if not out_trade_no:
            now = datetime.now()
            out_trade_no = '{0}{1}{2}'.format(
                self.mch_id,
                now.strftime('%Y%m%d%H%M%S'),
                random.randint(1000, 10000)
            )
        data = {
            'appid': self.appid,
            'coupon_stock_id': stock_id,
            'openid': user_id,
            'openid_count': 1,
            'partner_trade_no': out_trade_no,
            'op_user_id': op_user_id,
            'device_info': device_info,
            'version': '1.0',
            'type': 'XML',
        }
        return self._post('mmpaymkttransfers/send_coupon', data=data)
449042
def QA_util_get_trade_gap(start, end):
    ''
    start, end = QA_util_get_real_datelist(start, end)
    if start is not None:
        return trade_date_sse.index(end) + 1 - trade_date_sse.index(start)
    else:
        return 0
1160651
def cancel_entrust(self, entrust_no):
        
        xq_entrust_list = self._get_xq_history()
        is_have = False
        for xq_entrusts in xq_entrust_list:
            status = xq_entrusts["status"]  # 调仓状态
            for entrust in xq_entrusts["rebalancing_histories"]:
                if entrust["id"] == entrust_no and status == "pending":
                    is_have = True
                    buy_or_sell = (
                        "buy"
                        if entrust["target_weight"] < entrust["weight"]
                        else "sell"
                    )
                    if (
                        entrust["target_weight"] == 0
                        and entrust["weight"] == 0
                    ):
                        raise exceptions.TradeError(u"移除的股票操作无法撤销,建议重新买入")
                    balance = self.get_balance()[0]
                    volume = (
                        abs(entrust["target_weight"] - entrust["weight"])
                        * balance["asset_balance"]
                        / 100
                    )
                    r = self._trade(
                        security=entrust["stock_symbol"],
                        volume=volume,
                        entrust_bs=buy_or_sell,
                    )
                    if len(r) > 0 and "error_info" in r[0]:
                        raise exceptions.TradeError(
                            u"撤销失败!%s" % ("error_info" in r[0])
                        )
        if not is_have:
            raise exceptions.TradeError(u"撤销对象已失效")
        return True