CmBroker.php
32.7 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
<?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__ . '/exchange/bybit/ExBroker.php';
require_once __DIR__ . '/exchange/bitget/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__ . '/struct/Premium.php';
require_once __DIR__ . '/struct/IndexTicker.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\exchange\bybit\ExBroker as BybitBroker;
use trader\exchange\bitget\ExBroker as BitgetBroker;
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 trader\struct\Premium;
use trader\struct\IndexTicker;
use \Exception;
use function jytools\timeFormat;
use function jytools\getMicrotime;
class CmBroker
{
const PLAT_OKX = 'okx';
const PLAT_BINANCE = 'binance';
const PLAT_BYBIT = 'bybit';
const PLAT_BITGET = 'bitget';
const BN_FEE_KEY = "x-tdk3UjFd";
const OK_FEE_KEY = "059de09b75e8BCDE";
const MODE_TWO_SIDE = 'TWO_SIDE';
const MODE_ONE_SIDE = 'ONE_SIDE';
/**
* @var string 当前使用的交易平台
* @see PLAT_OKX
* @see PLAT_BINANCE
* @see PLAT_BYBIT
* @see PLAT_BITGET
*/
public $plat;
private OkxBroker|BinanceBroker|BybitBroker|BitgetBroker $exBroker;
/** @var SymbolInfo[] $symbolInfos */
public $symbolInfos = [];
/** @var Pos[] $positions */
public $positions = [];
public $name = '';
public $levers = [];
public $uid;
public $posMode = '';
public ?ApiInfo $apiInfo;
private $wsHost;
private $restHost;
public function __construct($plat, ?ApiInfo $apiInfo, $wsHost = null, $restHost = null)
{
$this->plat = $plat;
$this->apiInfo = $apiInfo;
$exBroker = null;
if ($plat == self::PLAT_OKX) {
$exBroker = new OkxBroker($apiInfo);
}
if ($plat == self::PLAT_BINANCE) {
$exBroker = new BinanceBroker($apiInfo);
}
if ($plat == self::PLAT_BYBIT) {
$exBroker = new BybitBroker($apiInfo);
}
if ($plat == self::PLAT_BITGET) {
$exBroker = new BitgetBroker($apiInfo);
}
$this->wsHost = $wsHost;
$this->restHost = $restHost;
$this->exBroker = $exBroker;
if ($wsHost && $wsHost != "") {
$this->exBroker->setWsHost($wsHost);
}
if ($restHost && $restHost != "") {
$this->exBroker->setRestHost($restHost);
}
$this->init();
}
//复制一个新的实例
public function copy()
{
$apiInfo = null;
if ($this->apiInfo) {
$apiInfo = new ApiInfo($this->apiInfo->key, $this->apiInfo->secret, $this->apiInfo->passphrase);
}
$cmBroker = new CmBroker($this->plat, $apiInfo, $this->wsHost, $this->restHost);
$cmBroker->symbolInfos = $this->symbolInfos;
$cmBroker->positions = $this->positions;
$cmBroker->name = $this->name;
$cmBroker->levers = $this->levers;
$cmBroker->uid = $this->uid;
$cmBroker->posMode = $this->posMode;
return $cmBroker;
}
public function setName($name)
{
$this->name = $name;
}
public function setUid($uid)
{
$this->uid = $uid;
}
public function init()
{
$this->initSymbolInfos();
if ($this->plat == self::PLAT_OKX && $this->apiInfo && $this->apiInfo->key != '') {
$this->initPosMode();
$this->initPositions();
}
}
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);
}
if ($this->plat == self::PLAT_BYBIT) {
$this->bybitAccDataHandle($data, $onData);
}
if ($this->plat == self::PLAT_BITGET) {
$this->bitgetAccDataHandle($data, $onData);
}
});
}
//处理币安相关账户数据监听
private function binanceAccDataHandle($data, $onData)
{
if (isset($data['e']) && $data['e'] == 'ORDER_TRADE_UPDATE') {
if ($data['o']['x'] == 'TRADE') {
$wsDataTrade = WsDataTrade::TransferBinanceTrade($data, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
if ($wsDataTrade != null) {
$wsDataTrade->cliOrdId = str_replace(self::BN_FEE_KEY, '', $wsDataTrade->cliOrdId);
$wsData = new WsData($this->plat, 'trade', $trade = $wsDataTrade);
$onData($wsData);
}
}
$wsDataOrder = WsDataOrder::TransferBinanceOrder($data, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
if ($wsDataOrder != null) {
$wsDataOrder->cliOrdId = str_replace(self::BN_FEE_KEY, '', $wsDataOrder->cliOrdId);
$wsData = new WsData($this->plat, 'order', $trade = null, $pos = null, $order = $wsDataOrder);
$onData($wsData);
}
}
if (isset($data['e']) && $data['e'] == 'ACCOUNT_UPDATE') {
if (isset($data['a']) && isset($data['a']['P'])) {
$positions = $data['a']['P'];
foreach ($positions as $key => $value) {
$wsDataPos = WsDataPos::TransferBinancePos($value, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
$this->positions[$wsDataPos->symbol . "_" . $wsDataPos->posSide] = $wsDataPos;
$wsData = new WsData($this->plat, 'pos', $trade = null, $pos = $wsDataPos);
$onData($wsData);
}
foreach ($this->positions as $key => $value) {
if ($value->qty == 0) {
unset($this->positions[$key]);
}
}
}
}
}
//处理欧意账户相关数据监听
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);
if ($this->posMode != self::MODE_ONE_SIDE) {
$pos->qty = abs($pos->qty); // 统一为正
$pos->lot = abs($pos->lot); // 统一为正
}
$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);
}
//处理bybit账户相关数据监听
private function bybitAccDataHandle($data, $onData)
{
if (isset($data['topic']) && $data['topic'] == 'order') {
foreach ($data['data'] as $key => $value) {
$wsDataOrd = WsDataOrder::TransferBybitOrder($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['topic']) && $data['topic'] == 'execution') {
foreach ($data['data'] as $key => $value) {
$wsDataTrade = WsDataTrade::TransferBybitTrade($value, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
if ($wsDataTrade != null) {
$wsData = new WsData($this->plat, 'trade', $trade = $wsDataTrade);
$onData($wsData);
}
}
return;
}
if (isset($data['topic']) && $data['topic'] == 'position') {
foreach ($data['data'] as $key => $value) {
$wsDataPos = WsDataPos::TransferBybitPos($value, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
if ($wsDataPos != null) {
$pos = Pos::transferWsDataPos($wsDataPos);
$this->positions[$wsDataPos->symbol . "_" . $wsDataPos->posSide] = $pos;
$wsData = new WsData($this->plat, 'pos', $trade = null, $pos = $wsDataPos);
$onData($wsData);
}
}
return;
}
}
//处理bitget账户相关数据监听
private function bitgetAccDataHandle($data, $onData)
{
// 处理订单和成交数据
if (isset($data['arg']) && $data['arg']['channel'] == 'orders') {
foreach ($data['data'] as $value) {
// 处理订单数据
$wsDataOrder = WsDataOrder::TransferBitgetOrder($value, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
if ($wsDataOrder) {
$wsData = new WsData($this->plat, 'order', null, null, $wsDataOrder);
$onData($wsData);
}
}
return;
}
//处理成交数据
if (isset($data['arg']) && $data['arg']['channel'] == 'fill') {
foreach ($data['data'] as $value) {
$wsDataTrade = WsDataTrade::TransferBitgetOrder($value, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
if ($wsDataTrade) {
$wsData = new WsData($this->plat, 'trade', $wsDataTrade);
$onData($wsData);
}
}
}
// 处理持仓数据
if (isset($data['arg']) && $data['arg']['channel'] == 'positions') {
foreach ($data['data'] as $pos) {
$wsDataPos = WsDataPos::TransferBitgetPos($pos, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
if ($wsDataPos) {
$this->positions[$wsDataPos->symbol . "_" . $wsDataPos->posSide] = $wsDataPos;
$wsData = new WsData($this->plat, 'pos', null, $wsDataPos);
$onData($wsData);
}
}
return;
}
}
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);
$periodOri = $this->getPeriodOri($this->plat, $peroid);
$this->exBroker->klineListen($symbol, $periodOri, function ($data) use ($onData) {
if ($this->plat == self::PLAT_BINANCE) {
$kline = Kline::transferBinance($data);
}
if ($this->plat == self::PLAT_OKX) {
$kline = Kline::transferOkx($data);
}
if ($this->plat == self::PLAT_BYBIT) {
$kline = Kline::transferBybit($data);
}
if ($this->plat == self::PLAT_BITGET) {
$kline = Kline::transferBitget($data);
}
$onData($kline);
});
}
//转换为标准交易对
public function getSymbolSt($symbol)
{
$symbol = str_replace('-USDT-SWAP', 'USDT', $symbol);
$symbol = str_replace('-USDC-SWAP', 'USDC', $symbol);
if (preg_match('/^[A-Z0-9]+USD[CT]$/', $symbol)) {
if ($this->plat == self::PLAT_BINANCE || $this->plat == self::PLAT_BYBIT) {
$num = SymbolInfo::extractNumber($symbol);
$symbol = str_replace($num, '', $symbol);
return $symbol;
}
return $symbol;
} else {
throw new Exception('转换标准交易对错误' . $symbol . ' to ', $symbol);
}
}
//转换为原始周期
public function getPeriodOri($platTarget, $period)
{
if ($platTarget == self::PLAT_BINANCE) {
return $period;
}
if ($platTarget == self::PLAT_OKX) {
$arr = [
'1s' => '1s',
'1m' => '1m',
'3m' => '3m',
'5m' => '5m',
'15m' => '15m',
'30m' => '30m',
'1h' => '1H',
'2h' => '2H',
'4h' => '4H',
'6h' => '6H',
'12h' => '12H',
'1d' => '1D',
'1w' => '1W',
];
if (!isset($arr[$period])) {
throw new Exception('周期错误,' . $this->plat . '不支持的周期' . $period);
}
return $arr[$period];
}
if ($platTarget == self::PLAT_BYBIT) {
$arr = [
'1m' => '1',
'3m' => '3',
'5m' => '5',
'15m' => '15',
'30m' => '30',
'1h' => '60',
'2h' => '120',
'4h' => '240',
'6h' => '360',
'12h' => '720',
'1d' => 'D',
'1w' => 'W',
'1M' => 'M',
];
if (!isset($arr[$period])) {
throw new Exception('周期错误,' . $this->plat . '不支持的周期' . $period);
}
return $arr[$period];
}
if ($platTarget == self::PLAT_BITGET) {
$arr = [
'1m' => 'candle1m',
'5m' => 'candle5m',
'15m' => 'candle15m',
'30m' => 'candle30m',
'1h' => 'candle1H',
'4h' => 'candle4H',
'12h' => 'candle12H',
'1d' => 'candle1D',
];
if (!isset($arr[$period])) {
throw new Exception('周期错误,' . $this->plat . '不支持的周期' . $period);
}
return $arr[$period];
}
throw new Exception('平台错误' . $platTarget);
}
//转换为原始交易对
public function getSymbolOri($symbol): string
{
/** @var SymbolInfo $symbolInfo */
$symbolInfo = $this->symbolInfos[$symbol] ?? false;
if ($symbolInfo) {
return $symbolInfo->symbolOri;
}
return "";
}
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);
});
if (!isset($orderOri['tag'])) {
$orderOri['tag'] = self::OK_FEE_KEY;
}
$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);
});
if (isset($orderOri['newClientOrderId'])) {
$orderOri['newClientOrderId'] = self::BN_FEE_KEY . $orderOri['newClientOrderId'];
} else {
$orderOri['newClientOrderId'] = self::BN_FEE_KEY . getMicrotime();
}
$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);
if ($res && isset($res['clientOrderId'])) {
$res['clientOrderId'] = str_replace(self::BN_FEE_KEY, '', $res['clientOrderId']);
}
return $res;
}
if ($this->plat == self::PLAT_BYBIT) {
$orderOri = $order->toBybitOrder($this->symbolInfos, function ($symbol) {
return $this->getSymbolOri($symbol, $this->plat);
});
$this->msg("下单", $orderOri);
if ($orderOri['qty'] == 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_BITGET) {
$orderOri = $order->toBitgetOrder($this->symbolInfos, function ($symbol) {
return $this->getSymbolOri($symbol, $this->plat);
});
$this->msg("下单", $orderOri);
if ($orderOri['size'] == 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 $pos->qty;
}
private function initSymbolInfos($count = 1)
{
if ($count > 3) {
throw new Exception("broker初始化交易对信息失败");
}
if ($this->plat == self::PLAT_OKX) {
//获取所有USDT SWAP 交易对
$res = $this->exBroker->getSymbolInfos();
$infos = [];
foreach ($res as $key => $value) {
if (($value["settleCcy"] == "USDT" || $value["settleCcy"] == "USDC") && $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["quoteAsset"] == "USDC") && $value["status"] == "TRADING" && $value["contractType"] == "PERPETUAL") {
$info = SymbolInfo::transferBinance($value, function ($symbol) {
return $this->getSymbolSt($symbol);
});
$infos[$info->symbol] = $info;
}
}
$this->symbolInfos = $infos;
}
if ($this->plat == self::PLAT_BYBIT) {
$res = $this->exBroker->getSymbolInfos();
$infos = [];
foreach ($res as $key => $value) {
if (($value['quoteCoin'] == 'USDT') && $value['status'] == 'Trading' && $value['contractType'] == 'LinearPerpetual') {
$info = SymbolInfo::transferBybit($value, function ($symbol) {
return $this->getSymbolSt($symbol);
});
$infos[$info->symbol] = $info;
}
}
$this->symbolInfos = $infos;
}
if ($this->plat == self::PLAT_BITGET) {
$res = $this->exBroker->getSymbolInfos();
$infos = [];
foreach ($res as $value) {
if (($value['quoteCoin'] == 'USDT' || $value['quoteCoin'] == 'USDC') && $value['symbolStatus'] == 'normal') {
$info = SymbolInfo::transferBitget($value, function ($symbol) {
return $this->getSymbolSt($symbol);
});
$infos[$info->symbol] = $info;
}
}
$this->symbolInfos = $infos;
}
if (count($this->symbolInfos) == 0) {
$this->initSymbolInfos($count + 1);
return;
}
//定时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);
$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);
});
if ($this->posMode != self::MODE_ONE_SIDE) {
$item->qty = abs($item->qty);
$item->lot = abs($item->lot);
}
$newPositions[$item->symbol . "_" . $item->posSide] = $item;
}
if ($this->plat == self::PLAT_BINANCE) {
$item = Pos::transferBinancePos($value, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
if ($this->posMode != self::MODE_ONE_SIDE) {
$item->qty = abs($item->qty);
$item->lot = abs($item->lot);
}
$newPositions[$item->symbol . "_" . $item->posSide] = $item;
}
}
return $newPositions;
}
//获取某个品种的某个方向仓位
public function getPos($symbol, $posSide)
{
$symbolOri = $this->getSymbolOri($symbol);
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);
if ($this->posMode != self::MODE_ONE_SIDE) {
$qty = abs($qty);
$lot = abs($lot);
}
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);
$peroidOri = $this->getPeriodOri($this->plat, $peroid);
if ($this->plat == self::PLAT_OKX) {
$res = $this->exBroker->getKlines($symbolOri, $peroidOri, $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;
}
if ($this->plat == self::PLAT_BINANCE) {
$res = $this->exBroker->getKlines($symbolOri, $peroidOri, $limit);
if (count($res) == 0) {
return [];
}
$newKlines = [];
foreach ($res as $key => $value) {
$kline = Kline::transferBinanceRest($value);
$newKlines[] = $kline;
}
//把 $newKlines 倒序
$newKlines = array_reverse($newKlines);
return $newKlines;
}
return [];
}
public function initPositions()
{
$this->positions = $this->getAllPos();
}
//----------公告数据接口--------
//获取所有品种资金费率,返回数据为 Premium[]
public function getPremiumAll(): array
{
$data = [];
if ($this->plat == self::PLAT_OKX) {
foreach ($this->symbolInfos as $key => $value) {
$res = $this->exBroker->getPremium($value->symbolOri);
if (isset($res['data'])) {
$prem = Premium::transferOkx($res['data'][0], function ($symbol) {
return $this->getSymbolSt($symbol);
});
$data[$prem->symbol] = $prem;
}
}
} else if ($this->plat == self::PLAT_BINANCE) {
$res = $this->exBroker->getPremiumAll();
foreach ($res as $key => $value) {
$prem = Premium::transferBinance($value, function ($symbol) {
return $this->getSymbolSt($symbol);
});
if ($prem) {
$data[$prem->symbol] = $prem;
}
}
} else {
throw new Exception("获取资金费 该交易所未实现,请先实现代码");
}
return $data;
}
private function initPosMode()
{
if ($this->plat == self::PLAT_OKX && $this->apiInfo && $this->apiInfo->key != '') {
$res = $this->exBroker->getAccountConfig();
$config = $res['data'][0];
$this->posMode = $config['posMode'] == 'long_short_mode' ? self::MODE_TWO_SIDE : self::MODE_ONE_SIDE;
}
}
public function cancelOrder($symbol, $cliOrdId = "", $orderId = "")
{
$symbolOri = $this->getSymbolOri($symbol);
if ($this->plat == self::PLAT_OKX) {
return $this->exBroker->cancelOrder($symbolOri, $cliOrdId, $orderId);
}
}
public function getOrder($symbol, $cliOrdId = "", $orderId = ""): ?WsDataOrder
{
$symbolOri = $this->getSymbolOri($symbol);
if ($this->plat == self::PLAT_OKX) {
$res = $this->exBroker->getOrder($symbolOri, $cliOrdId, $orderId);
if (isset($res['data']) && isset($res['data'][0])) {
$data = $res['data'][0];
return WsDataOrder::TransferOkxOrder($data, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
}
}
return null;
}
public function getOrderPending($symbol): array
{
if ($this->plat == self::PLAT_OKX) {
$symbolOri = $this->getSymbolOri($symbol);
$res = $this->exBroker->getOrderPending($symbolOri);
if (isset($res['data']) && isset($res['data'][0])) {
$orders = [];
foreach ($res['data'] as $key => $value) {
$order = WsDataOrder::TransferOkxOrder($value, $this->symbolInfos, function ($symbol) {
return $this->getSymbolSt($symbol);
});
$orders[] = $order;
}
return $orders;
}
} else {
new Exception("getOrderPending 该交易所未实现,请先实现代码");
}
return [];
}
public function subDepth($symbol, callable $onData)
{
$this->exBroker->subDepth($symbol, $onData);
}
public function getIndexTickers()
{
$res = $this->exBroker->getIndexTickers();
if ($res && $res['code'] == '0') {
return IndexTicker::transferOkxData($res['data']);
}
return [];
}
}