东方财富API获取股票实时交易数据

 1 public function index()
 2     {
 3         //$list = [0.002849,0.002175,0.301198,0.002077,0.002953,0.002153,0.300052,0.002152,0.002520,0.000034,0.300348,0.000004,0.300333];
 4         $code = $this->request->get('code','600272|0');
 5         $list = explode(',',$code);
 6         //$list = [1.600272,0.300348];
 7         $codes = $tags = [];
 8         foreach($list as $val){
 9             $temp = explode('|',$val);
10             if(substr($temp[0],0,1)==6){
11                 array_push($codes,"1.".$temp[0]);
12                 array_push($tags,$temp[1]);
13             }else{
14                 array_push($codes,"0.".$temp[0]);
15                 array_push($tags,$temp[1]);
16             }
17         }
18         $row = $this->getInfo($codes, $tags);
19         $this->view->assign('row', $row);
20         return $this->view->fetch();
21     }
22 
23     function getInfo($codes = [1.600272],$tags = [0]){
24         $row = [];
25         foreach($codes as $k=>$val){
26             $stock_code = $val; //  '1.600272'; //0.300052//0.002175//1.600272
27 
28             // API URL
29             $url = "https://push2.eastmoney.com/api/qt/stock/get?secid=".$stock_code;
30       
31             // 获取数据
32             $response = Http::get($url);
33             // 解析数据
34             if ($response) {
35                 $data = json_decode($response, true);
36                 if ($data['data']) {
37                    $currentPrice = $data['data']['f43']/100; //现价
38                    $initialPrice = $data['data']['f60']/100; //昨收
39                    // 计算涨幅百分比
40                    $priceChange = $currentPrice - $initialPrice;
41                    $percentChange = ($priceChange / $initialPrice) * 100;
42                    $row[] = [
43                         'code' => $stock_code,
44                         'name' => $data['data']['f58'],//名称
45                         'price' => $currentPrice,
46                         'volume' => number_format($data['data']['f47']/10000,2), //总量
47                         'average_price' => $data['data']['f71']/100, //均价
48                         'per_price' => $initialPrice,
49                         'rate'=> number_format($percentChange, 2), //涨幅
50                         'tag' => $tags[$k],
51                    ];                   
52                 } 
53             } else {
54                $row[] = [];
55             }
56         }
57         return $row;
58     }

 

posted @ 2025-02-10 15:07  王默默  阅读(755)  评论(0)    收藏  举报