作者 karlet

feat:增加平仓

@@ -214,4 +214,8 @@ class CmBroker @@ -214,4 +214,8 @@ class CmBroker
214 { 214 {
215 $this->exBroker->stopListen(); 215 $this->exBroker->stopListen();
216 } 216 }
  217 + public function closeAllPos()
  218 + {
  219 + $this->exBroker->closeAllPos();
  220 + }
217 } 221 }
@@ -84,6 +84,13 @@ class Api @@ -84,6 +84,13 @@ class Api
84 $method = 'GET'; 84 $method = 'GET';
85 return $this->request($path, $method, $param, $this->apiInfo); 85 return $this->request($path, $method, $param, $this->apiInfo);
86 } 86 }
  87 + //查询持仓
  88 + public function getPositions($param)
  89 + {
  90 + $path = '/api/v5/account/positions';
  91 + $method = 'GET';
  92 + return self::request($path, $method, $param, $this->apiInfo);
  93 + }
87 94
88 //------------------------------------- 95 //-------------------------------------
89 96
@@ -178,4 +178,38 @@ class ExBroker @@ -178,4 +178,38 @@ class ExBroker
178 $this->wsAcc->close(); 178 $this->wsAcc->close();
179 $this->wsKline->close(); 179 $this->wsKline->close();
180 } 180 }
  181 + public function closeAllPos()
  182 + {
  183 + //获取所有仓位
  184 + $param = [
  185 + 'instType' => 'SWAP'
  186 + ];
  187 + $res = $this->api->getPositions($param);
  188 + if ($res['code'] == 0) {
  189 + $positions = $res['data'];
  190 + foreach ($positions as $key => $value) {
  191 + if ($value['pos'] != 0) {
  192 + $this->clsoePos($value['instId'], $value['posSide'], abs($value['pos']), $value['mgnMode']);
  193 + }
  194 + }
  195 + }
  196 + }
  197 + // 平仓
  198 + private function clsoePos($instId, $posSide, $size, $tdMode)
  199 + {
  200 + $param = [
  201 + 'instId' => $instId,
  202 + 'tdMode' => $tdMode,
  203 + 'side' => strtoupper($posSide) == 'LONG' ? 'sell' : 'buy',
  204 + 'posSide' => $posSide,
  205 + 'ordType' => 'market',
  206 + 'sz' => $size,
  207 + ];
  208 + $res = $this->api->placeOrder($param);
  209 + if ($res['code'] == 0) {
  210 + return true;
  211 + } else {
  212 + return false;
  213 + }
  214 + }
181 } 215 }