CmBroker.php 14.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
<?php

namespace trader;

require_once __DIR__ . '/struct/ApiInfo.php';
require_once __DIR__ . '/exchange/okx/ExBroker.php';
require_once __DIR__ . '/exchange/binance/ExBroker.php';
require_once __DIR__ . '/struct/Kline.php';
require_once __DIR__ . '/struct/Order.php';
require_once __DIR__ . '/struct/WsData.php';
require_once __DIR__ . '/struct/WsDataTrade.php';
require_once __DIR__ . '/struct/WsDataPos.php';
require_once __DIR__ . '/struct/SymbolInfo.php';
require_once __DIR__ . '/struct/WsDataOrder.php';
require_once __DIR__ . '/struct/WsDataAccount.php';
require_once __DIR__ . '/struct/Pos.php';
require_once __DIR__ . '/../jytools/func.php';
require_once __DIR__ . '/../jytools/Websocket.php';


use trader\struct\ApiInfo;
use trader\exchange\okx\ExBroker as OkxBroker;
use trader\exchange\binance\ExBroker as BinanceBroker;
use trader\struct\Kline;
use trader\struct\Order;
use trader\struct\WsData;
use trader\struct\WsDataTrade;
use trader\struct\WsDataPos;
use trader\struct\SymbolInfo;
use trader\struct\WsDataOrder;
use trader\struct\WsDataAccount;
use trader\struct\Pos;
use \Exception;
use function jytools\timeFormat;

class CmBroker
{
    const PLAT_OKX = 'okx';
    const PLAT_BINANCE = 'binance';
    const PLAT_BYBIT = 'bybit';
    const PLAT_BITGET = 'bitget';
    /**
     * @var string 当前使用的交易平台
     * @see PLAT_OKX
     * @see PLAT_BINANCE
     * @see PLAT_BYBIT 
     * @see PLAT_BITGET
     */
    public $plat;
    private OkxBroker|BinanceBroker $exBroker;
    /** @var SymbolInfo[] $symbolInfos */
    public $symbolInfos = [];
    /** @var Pos[] $positions */
    public $positions = [];
    public $name = '';
    public $levers = [];
    public $uid;


    public function __construct($plat, ApiInfo $apiInfo)
    {
        $this->plat = $plat;
        $exBroker = null;
        if ($plat == self::PLAT_OKX) {
            $exBroker = new OkxBroker($apiInfo);
        }
        if ($plat == self::PLAT_BINANCE) {
            $exBroker = new BinanceBroker($apiInfo);
        }
        $this->exBroker = $exBroker;
    }
    public function setWsHost($host)
    {
        $this->exBroker->setWsHost($host);
    }
    public function setRestHost($host)
    {
        $this->exBroker->setRestHost($host);
    }
    public function setName($name)
    {
        $this->name = $name;
    }
    public function setUid($uid)
    {
        $this->uid = $uid;
    }
    public function init()
    {
        $this->initSymbolInfos();
    }
    public function accListen(callable $onData)
    {
        $this->exBroker->accListen(function ($data) use ($onData) {
            // output("ws 有效数据", $data);
            if ($this->plat == self::PLAT_BINANCE) {
                $this->binanceAccDataHandle($data, $onData);
            }
            if ($this->plat == self::PLAT_OKX) {
                $this->okxAccDataHandle($data, $onData);
            }
        });
    }
    //处理币安相关账户数据监听
    private function binanceAccDataHandle($data, $onData)
    {
        $this->msg("binance 推送", $data);
    }
    //处理欧意账户相关数据监听
    private function okxAccDataHandle($data, $onData)
    {
        if (isset($data['arg']) && $data['arg']['channel'] == 'orders') {
            foreach ($data['data'] as $key => $value) {
                $wsDataTrade = WsDataTrade::TransferOkxOrder($value, $this->symbolInfos, function ($symbol) {
                    return $this->getSymbolSt($symbol);
                });
                if ($wsDataTrade != null) {
                    $wsData = new WsData($this->plat, 'trade', $trade = $wsDataTrade);
                    $onData($wsData);
                }
                $wsDataOrd = WsDataOrder::TransferOkxOrder($value, $this->symbolInfos, function ($symbol) {
                    return $this->getSymbolSt($symbol);
                });
                if ($wsDataOrd != null) {
                    $wsData = new WsData($this->plat, 'order', $trade = null, $pos = null, $order = $wsDataOrd);
                    $onData($wsData);
                }
            }
            return;
        }
        if (isset($data['arg']) && $data['arg']['channel'] == 'positions') {
            $positions = [];
            $eventType = $data['eventType'];
            foreach ($data['data'] as $key => $value) {
                $wsDataPos = WsDataPos::TransferOkxPos($value, $this->symbolInfos, function ($symbol) {
                    return $this->getSymbolSt($symbol);
                });
                if ($wsDataPos) {
                    $pos = Pos::transferWsDataPos($wsDataPos);
                    $positions[$wsDataPos->symbol . "_" . $wsDataPos->posSide] = $pos;
                    $wsData = new WsData($this->plat, 'pos', $trade = null, $pos = $wsDataPos);
                    $onData($wsData);
                    if ($eventType == 'event_update') {
                        $this->positions[$wsDataPos->symbol . "_" . $wsDataPos->posSide] = $pos;
                    }
                }
            }
            if ($eventType == 'snapshot') {
                $this->positions = $positions;
            }
            return;
        }
        if (isset($data['arg']) && $data['arg']['channel'] == 'account') {
            $wsDataAccount = WsDataAccount::TransferOkxAccount($data['data']);
            $wsData = new WsData($this->plat, 'account', $trade = null, $pos = null, $order = null, $account = $wsDataAccount);
            $onData($wsData);
            return;
        }
        $this->msg("okx 无处理ws数据实现", $data);
    }
    public function klineListen($symbol, $peroid, $onData)
    {
        if ($this->plat == self::PLAT_BINANCE && $peroid == '1s') {
            $this->msg("币安不支持1sk线", $symbol, $peroid);
            return;
        }
        $symbol = $this->getSymbolOri($symbol, $this->plat);
        $this->exBroker->klineListen($symbol, $peroid, function ($data) use ($onData) {
            if ($this->plat == self::PLAT_BINANCE) {
                $kline = Kline::transferBinance($data);
            }
            if ($this->plat == self::PLAT_OKX) {
                $kline = Kline::transferOkx($data);
            }
            $onData($kline);
        });
    }
    //转换为标准交易对
    public function getSymbolSt($symbol)
    {
        $symbol = str_replace('-USDT-SWAP', 'USDT',  $symbol);
        if (preg_match('/^[A-Z0-9]+USDT$/', $symbol)) {
            return $symbol;
        } else {
            throw new Exception('转换标准交易对错误' . $symbol . ' to ', $symbol);
        }
    }

    //转换为原始交易对
    public function getSymbolOri($symbol, $platTarget)
    {
        $symbolSt = $this->getSymbolSt($symbol);
        if ($platTarget == self::PLAT_BINANCE) {
            return $symbolSt;
        }
        if ($platTarget == self::PLAT_OKX) {
            return str_replace('USDT', '-USDT-SWAP', $symbolSt);
        }
        throw new Exception('平台错误' + $platTarget);
    }

    public function placeOrder(Order $order)
    {
        /** @var SymbolInfo $symbolInfo */
        $symbolInfo = $this->symbolInfos[$order->symbol];
        if ($this->plat == self::PLAT_OKX) {
            $orderOri = $order->toOkxOrder($this->symbolInfos, function ($symbol) {
                return $this->getSymbolOri($symbol, $this->plat);
            });
            $this->msg("下单", $orderOri);
            if ($orderOri['sz'] == 0) {
                $msg = "当前下单数量为{$order->qty},最小下单数量为{$symbolInfo->minQty},不下单";
                $this->msg($msg, $orderOri);
                return ["code" => 2, "msg" => $msg];
            }
            $res = $this->exBroker->placeOrder($orderOri);
            $this->msg("下单结果", $res);
            return $res;
        }
        if ($this->plat == self::PLAT_BINANCE) {
            $orderOri = $order->toBinanceOrder($this->symbolInfos, function ($symbol) {
                return $this->getSymbolOri($symbol, $this->plat);
            });
            $this->msg("下单", $orderOri);
            if ($orderOri['quantity'] == 0) {
                $msg = "当前下单数量为{$order->qty},最小下单数量为{$symbolInfo->minQty},不下单";
                $this->msg($msg, $orderOri);
                return ["code" => 2, "msg" => $msg];
            }
            $res = $this->exBroker->placeOrder($orderOri);
            $this->msg("下单结果", $res);
            return $res;
        }
    }

    public function msg()
    {
        $args = func_get_args();
        $outStr = '[' . timeFormat('ms') . ']:' . $this->name . ": ";
        foreach ($args as $key => $value) {
            $value = is_array($value) ? json_encode($value) : $value;
            if (is_bool($value)) {
                $value = $value ? 'bool:true' : 'bool:false';
            }
            $outStr .= count($args) - $key > 1 ? $value . '  ' : $value;
        }
        echo $outStr . PHP_EOL;
    }
    public function getPosQty($symbol, $posSide)
    {
        $key = $symbol . "_" . $posSide;
        if (!isset($this->positions[$key])) {
            return 0;
        }
        /** @var Pos $pos */
        $pos = $this->positions[$key];
        return abs($pos->qty);
    }
    private function initSymbolInfos()
    {
        if ($this->plat == self::PLAT_OKX) {
            //获取所有USDT SWAP 交易对
            $res = $this->exBroker->getSymbolInfos();
            $infos = [];
            foreach ($res as $key => $value) {
                if ($value["settleCcy"] == "USDT" && $value["state"] == "live") {
                    $info = SymbolInfo::transferOkx($value, function ($symbol) {
                        return $this->getSymbolSt($symbol);
                    });
                    $infos[$info->symbol] = $info;
                }
            }
            $this->symbolInfos = $infos;
        }
        if ($this->plat == self::PLAT_BINANCE) {
            $res = $this->exBroker->getSymbolInfos();
            $infos = [];
            foreach ($res as $key => $value) {
                if ($value["quoteAsset"] == "USDT" && $value["status"] == "TRADING" && $value["contractType"] == "PERPETUAL") {
                    $info = SymbolInfo::transferBinance($value, function ($symbol) {
                        return $this->getSymbolSt($symbol);
                    });
                    $infos[$info->symbol] = $info;
                }
            }
            $this->symbolInfos = $infos;
        }
        //定时10m刷新
        swoole_timer_after(1000 * 60 * 10, function () {
            $this->initSymbolInfos();
        });
    }
    public function stopListen()
    {
        $this->exBroker->stopListen();
    }
    public function closeAllPos()
    {
        $this->exBroker->closeAllPos();
    }
    //设置允许合约
    public function setAllowFutures($isAllowFutures)
    {
        $this->exBroker->setAllowFutures($isAllowFutures);
    }
    //设置双向持仓模式
    public function setLongShortMode($isLongShort)
    {
        $this->exBroker->setLongShortMode($isLongShort);
    }
    //获取全部品种的杠杆
    public function getLevers()
    {
        $levers = $this->exBroker->getAllLevers();
        if ($this->plat == self::PLAT_OKX) {
            $resNew = [];
            foreach ($levers as $key => $value) {
                $symbol = $this->getSymbolSt($key); //转换为标准交易对
                $resNew[$symbol] = $value;
            }
            $levers = $resNew;
        }
        if ($this->plat == self::PLAT_BINANCE) {
            $resNew = [];
            foreach ($levers as $key => $value) {
                if (!str_ends_with($key, 'USDT')) {
                    continue;
                }
                $symbol = $this->getSymbolSt($key); //转换为标准交易对
                $resNew[$symbol] = $value;
            }
            $levers = $resNew;
        }
        $this->levers = $levers; //缓存levers
        return $levers;
    }
    //设置杠杆
    public function setLever($symbol, $lever)
    {
        $symbol = $this->getSymbolOri($symbol, $this->plat);
        $res = $this->exBroker->setLever($symbol, $lever);
        if ($res) {
            $this->levers[$symbol] = $lever;
        }
    }
    //查询获取全部持仓
    public function getAllPos(): array
    {
        $positions = $this->exBroker->getAllPos();
        $newPositions = [];
        foreach ($positions as $key => $value) {
            if ($this->plat == self::PLAT_OKX) {
                $item = Pos::transferOkxPos($value, $this->symbolInfos, function ($symbol) {
                    return $this->getSymbolSt($symbol);
                });
                $newPositions[$item->symbol . "_" . $item->posSide] = $item;
            }
            if ($this->plat == self::PLAT_BINANCE) {
                $item = Pos::transferBinancePos($value, $this->symbolInfos, function ($symbol) {
                    return $this->getSymbolSt($symbol);
                });
                $newPositions[$item->symbol . "_" . $item->posSide] = $item;
            }
        }
        return $newPositions;
    }
    //获取某个品种的某个方向仓位
    public function getPos($symbol, $posSide)
    {
        $symbolOri = $this->getSymbolOri($symbol, $this->plat);
        if ($this->plat == self::PLAT_OKX) {
            $posSide = strtolower($posSide);
            $symbolInfo = $this->symbolInfos[$symbol];
            $lot = $this->exBroker->getPos($symbolOri, $posSide);
            $qty = round($lot * $symbolInfo->ctVal, $symbolInfo->qtyPrec);
            return $qty;
        }
        return -1;
    }
    /**
     * 获取k线数据
     * @param string $symbol 交易对
     * @param string $peroid 周期
     * @param int $limit 限制数量
     * @return Kline[] 返回K线数组
     */
    public function getKlines($symbol, $peroid, $limit = 100)
    {
        $symbolOri = $this->getSymbolOri($symbol, $this->plat);
        if ($this->plat == self::PLAT_OKX) {
            $res = $this->exBroker->getKlines($symbolOri, $peroid, $limit);
            if ($res['code'] != '0') {
                return [];
            }
            $newKlines = [];
            foreach ($res['data'] as $key => $value) {
                $kline = Kline::transferOkx($value);
                $newKlines[] = $kline;
            }
            //把 $newKlines 倒序
            $newKlines = array_reverse($newKlines);
            return $newKlines;
        }
        return [];
    }
    public function initPositions()
    {
        $this->positions = $this->getAllPos();
    }
}