<?php
/**
 * PHP发送Json对象数据
 *
 * @param $url 请求url
 * @param $jsonStr 发送的json字符串
 * @return array
 */
function http_post_json($url, $jsonStr)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        )
    );
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return array($httpCode, $response);
}

/**
 * 获取复权因子
 * @return array
 */
function getAdj(){
    $url = "http://api.waditu.com";
    $param['api_name']='adj_factor';
    $param['token']='1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
    $param['params'] = array('ts_code' => ts_code_conv($_REQUEST['ts_code']),
        'start_date'=>str_replace('-','',$_REQUEST['t_start']),
        'end_date'=>str_replace('-','',$_REQUEST['t_end'])
    );
    $param['fields'] ="";
    $jsonStr=json_encode($param);
    list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
    $arr = json_decode($returnContent,true);
    $items = $arr['data']['items'];
    $lastAdj=$items[0][2];
    foreach ($items as $t){
        list($ts_code,$date,$adj)=$t;
        $rt[$date]=$adj/$lastAdj;
    }
    return $rt;
}



/**
 * 获取个股融资融券余额信息
 * @return mixed
 */
function getMarginByCode(){
    $url = "http://api.waditu.com";
    $param['api_name']='margin_detail';
    $param['token']='1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
    $param['params'] = array('ts_code' => ts_code_conv($_REQUEST['ts_code']),
        'start_date'=>str_replace('-','',$_REQUEST['t_start']),
        'end_date'=>str_replace('-','',$_REQUEST['t_end'])
    );
    $param['fields'] ="";
    $jsonStr=json_encode($param);
    list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
    $arr = json_decode($returnContent,true);
    return  $arr['data'];
}

/**
 * @param $exchange SSE OR SZSE, set null for all
 * @return mixed
 */
function getMarginAll($exchange){

    $url = "http://api.waditu.com";
    $param['api_name']='margin_detail';
    $param['token']='1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
    $param['params'] = array(
        'start_date'=>str_replace('-','',$_REQUEST['t_start']),
        'end_date'=>str_replace('-','',$_REQUEST['t_end']),
        'exchange_id'=>$exchange
    );
    $param['fields'] ="";
    $jsonStr=json_encode($param);
    list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
    $arr = json_decode($returnContent,true);
    return  $arr['data'];
}

/**
 * 沪深港通资金流向
 * @return mixed
 */
function getMoneyFlowHSGT(){
    $url = "http://api.waditu.com";
    $param['api_name']='moneyflow_hsgt';
    $param['token']='1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
    $param['params'] = array(
        'start_date'=>'20200601',
        'end_date'=>date('Ymd')
    );
    $param['fields'] ="";
    $jsonStr=json_encode($param);
    list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
    $arr = json_decode($returnContent,true);
    return  $arr['data'];
}

/**
 * 获取A股个股香港资金持股每日数据
 * @return mixed
 */
function getHKHoldByCode(){
    $url = "http://api.waditu.com";
    $param['api_name']='hk_hold';
    $param['token']='1bc28452ba375da19320cda845ae6307578964cb3ae473d0dc702aea';
    $param['params'] = array(
        'ts_code' => ts_code_conv($_REQUEST['ts_code']),
        'start_date'=>str_replace('-','',$_REQUEST['t_start']),
        'end_date'=>str_replace('-','',$_REQUEST['t_end'])
    );
    $param['fields'] ="";
    $jsonStr=json_encode($param);
    list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
    $arr = json_decode($returnContent,true);
    return  $arr['data'];
}
/**
 * 使用复权因子对股价和成交股数进行复权
 * @param $adj
 * @param $data
 * @return mixed
 */
function adjData($adj,$data){
    $num = count($data);
    for($i=0;$i<$num;$i++){
        $t = str_replace('-','',$data[$i]['tdate']);
        $data[$i]['tprice']=round($data[$i]['tprice']*$adj[$t],3);
        $data[$i]['tvol']=round($data[$i]['tvol']/$adj[$t],0);
    }
    return $data;
}
/**
 *
0] => trade_date
[1] => ts_code
[2] => rzye
[3] => rqye
[4] => rzmre
[5] => rqyl
[6] => rzche
[7] => rqchl
[8] => rqmcl
[9] => rzrqye
https://tushare.pro/document/2?doc_id=58
 */
function marginByCodeReform($data){
    $data['items']=array_reverse($data['items']);
    foreach($data['items'] as $rec){
        $dataRT[]=array('value'=>array(date('Y-m-d',strtotime($rec[0])),$rec[9]/10000/10000));
        $val[]=$rec[9]/10000/10000;
    }
    $data_last= round($val[count($val)-1],2);
    $data_max= round(max($val),2);
    $data_min= round(min($val),2);
    if(count($val)>0) $data_avg= round(array_sum($val)/count($val),2);
    else $data_avg=null;
    return array('data'=>$dataRT,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}


/**
 * 计算累积值
 * @param $data
 * @return array
 */
function moneyFlowStacked($data){
    $keys=array_keys($data['fields']);
    $num = count($data['items']);
    foreach ($keys as $key) {
        $tmp = 0;
        for($i=0; $i<$num; $i++){
            //keep trade_date field NOT changed.
            if($key > 0)$tmp += $data['items'][$i][$key];
            else $tmp = $data['items'][$i][$key];
            $items[$i][$key]=$tmp;
        }
    }
    return array('fields'=>$data['fields'],'items'=>$items);
}

/**
 * 根据日期截取数据
 * @param $data
 * @param $s start date yyyymmdd
 * @param $e end date yyyymmdd
 * @return array|false
 */
function moneyFlowDateFilter($data,$s,$e){
    if($s>$e) return false;
    $num = count($data['items']);
    $items = array();
    for($i=0;$i<$num;$i++){
        if($data['items'][$i][0]>= $s and $data['items'][$i][0]<= $e)
            $items[]=$data['items'][$i];
    }
    return array('fields'=>$data['fields'],'items'=>$items);
}

/**
 *$hsgt :
 [0] => trade_date
[1] => ggt_ss
[2] => ggt_sz
[3] => hgt
[4] => sgt
[5] => north_money
[6] => south_money
 */
function moneyFlowReform($data,$hsgt){
    $data['items']=array_reverse($data['items']);
    $key = array_search($hsgt,$data['fields']);
    foreach($data['items'] as $rec){
        $dataRT[]=array('value'=>array(date('Y-m-d',strtotime($rec[0])),$rec[$key]/100));
        $val[]=$rec[$key]/100; //单位：亿元
    }
    $data_last= round($val[count($val)-1],2);
    $data_max= round(max($val),2);
    $data_min= round(min($val),2);
    if(count($val)>0) $data_avg= round(array_sum($val)/count($val),2);
    else $data_avg=null;
    return array('data'=>$dataRT,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}
/**
 * $hkhold:
 * 0 code
 * 1 trade_date
 * 2 ts_code
 * 3 name
 * 4 vol
 * 5 ratio
 * 6 exchange
 *
 */
function hkHoldReform($data,$hkhold){
    //print_r($data);
    $data['items']=array_reverse($data['items']);
    $key = array_search($hkhold,$data['fields']);
    foreach($data['items'] as $rec){
        if($hkhold=='vol') $rec[$key] = $rec[$key]/10000; //万股
        $dataRT[]=array('value'=>array(date('Y-m-d',strtotime($rec[1])),$rec[$key]));
        $val[]=$rec[$key];
    }
    $data_last= round($val[count($val)-1],2);
    $data_max= round(max($val),2);
    $data_min= round(min($val),2);
    if(count($val)>0) $data_avg= round(array_sum($val)/count($val),2);
    else $data_avg=null;
    return array('data'=>$dataRT,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}