作者 karlet

feat:路径调整与格式化

<?php
require_once __DIR__ . '/../src/Feishu.php';
require_once __DIR__ . '/../jytools/load.php';
use jytools\Feishu;
... ...
<?php
require_once __DIR__ . '/../src/Logger.php';
require_once __DIR__ . '/../jytools/load.php';
use jytools\Logger;
... ...
<?php
namespace jytools;
class Auth
... ... @@ -81,5 +82,4 @@ class Auth
return $ustr;
}
}
}
\ No newline at end of file
}
... ...
<?php
namespace jytools;
/*
binance合约接口
*/
class BinanceFutures
{
static private string $host = 'https://fapi.binance.com';
private string $apikey = '';
private string $secret = '';
public function __construct($apikey='', $secret='',$host='')
public function __construct($apikey = '', $secret = '', $host = '')
{
$this->apikey = $apikey;
$this->secret = $secret;
if(!empty($host)){
if (!empty($host)) {
self::$host = $host;
}
}
... ... @@ -42,9 +44,9 @@ class BinanceFutures
public function requestAccount($method, $path, $param)
{
if(empty($this->apikey) || empty($this->secret)){
if (empty($this->apikey) || empty($this->secret)) {
output('api 或 secret 为空');
return ['code'=>-1,'msg'=>'apikey or secret is empty'];
return ['code' => -1, 'msg' => 'apikey or secret is empty'];
}
$url = $this->createUrl($path);
$param['timestamp'] = getMicrotime();
... ... @@ -246,5 +248,3 @@ class BinanceFutures
return self::requestMarket($method, $path, $param);
}
}
?>
\ No newline at end of file
... ...
<?php
namespace jytools;
/*
binance现货接口
*/
class BinanceSpot
{
static private string $host = 'https://api.binance.com';
private string $apikey = '';
private string $secret = '';
public function __construct($apikey='', $secret='',$host='')
public function __construct($apikey = '', $secret = '', $host = '')
{
$this->apikey = $apikey;
$this->secret = $secret;
if(!empty($host)){
if (!empty($host)) {
self::$host = $host;
}
}
... ... @@ -33,7 +35,7 @@ class BinanceSpot
{
$len = count($param);
if ($len == 0) {
// output('param 为空,签名失败');
// output('param 为空,签名失败');
return $param;
}
$paramStr = http_build_query($param);
... ... @@ -65,7 +67,7 @@ class BinanceSpot
private function requestListenKey($method, $path, $param)
{
$url = $this->createUrl($path);
// $param['timestamp'] = getMicrotime();
// $param['timestamp'] = getMicrotime();
$param['signature'] = $this->createSign($this->secret, $param);
$header = $this->createHeader($this->apikey);
if (!in_array(strtoupper($method), ['GET', 'POST', 'DELETE'])) {
... ... @@ -112,14 +114,14 @@ class BinanceSpot
* @param int $type (=1:行情等接口,不需要签名;=2:账户等接口需要签名)
* @return array|int|mixed
*/
public function request(string $path, string $method, array $param, int $type=1)
public function request(string $path, string $method, array $param, int $type = 1)
{
if($type==2){
if ($type == 2) {
return self::requestAccount($method, $path, $param);
}else if($type==1){
} else if ($type == 1) {
return self::requestMarket($method, $path, $param);
}else{
return ['code'=>1000,'msg'=>'type参数错误'];
} else {
return ['code' => 1000, 'msg' => 'type参数错误'];
}
}
... ... @@ -207,13 +209,15 @@ class BinanceSpot
return $this->requestAccount($method, $path, $param);
}
public function cancelOrderById($param){
public function cancelOrderById($param)
{
$path = '/api/v3/order';
$method = 'DELETE';
return $this->requestAccount($method, $path, $param);
}
public function openOrders($param){
public function openOrders($param)
{
$path = '/api/v3/openOrders';
$method = 'GET';
return $this->requestAccount($method, $path, $param);
... ... @@ -232,25 +236,29 @@ class BinanceSpot
return $this->requestListenKey($method, $path, $param);
}
//杠杆账户下单
public function orderMargin($param){
public function orderMargin($param)
{
$path = '/sapi/v1/margin/order';
$method = 'POST';
return $this->requestAccount($method, $path, $param);
}
//杠杆账户撤销订单 (TRADE)
public function cancelOrderMargin($param){
public function cancelOrderMargin($param)
{
$path = '/sapi/v1/margin/order';
$method = 'DELETE';
return $this->requestAccount($method, $path, $param);
}
//杠杆账户订单列表
public function openOrdersMargin($param){
public function openOrdersMargin($param)
{
$path = '/sapi/v1/margin/openOrders';
$method = 'GET';
return $this->requestAccount($method, $path, $param);
}
//调整全仓最大杠杆 (USER_DATA)
public function maxLeverageMargin($param){
public function maxLeverageMargin($param)
{
$path = '/sapi/v1/margin/max-leverage';
$method = 'POST';
return $this->requestAccount($method, $path, $param);
... ... @@ -262,13 +270,11 @@ class BinanceSpot
* ==================================
*/
//24小时成交数据
// static public function ticker24hr($param = [])
// {
// $path = '/fapi/v1/ticker/24hr';
// $method = 'GET';
// return self::requestMarket($method, $path, $param);
// }
// static public function ticker24hr($param = [])
// {
// $path = '/fapi/v1/ticker/24hr';
// $method = 'GET';
// return self::requestMarket($method, $path, $param);
// }
}
?>
\ No newline at end of file
... ...
<?php
namespace jytools;
class Feishu{
class Feishu
{
const user_liquid = 'gd1d6b34';
const user_jiaoyin = 'efdgdecb';
const user_small = 'db9d9g4d';
... ... @@ -9,13 +11,13 @@ class Feishu{
const user_tanli = 'f16c2bd7';
const user_007 = '9de6cgf3';
//风控处置群
const url_risk ='https://open.feishu.cn/open-apis/bot/v2/hook/7509c731-a1ab-4e2f-b781-9082a26fd11d';
const url_risk = 'https://open.feishu.cn/open-apis/bot/v2/hook/7509c731-a1ab-4e2f-b781-9082a26fd11d';
//零容忍
const url_error = 'https://open.feishu.cn/open-apis/bot/v2/hook/a344e313-4d5d-4aa4-912b-dda37b2e3ee8';
//零忽略
const url_warning = 'https://open.feishu.cn/open-apis/bot/v2/hook/01c53b94-378a-45a3-abed-415f84f57f4a';
//软件异常报警
const url_warning_soft ='https://open.feishu.cn/open-apis/bot/v2/hook/d48c2e4a-0ef9-4684-88d4-e62d878fdaca';
const url_warning_soft = 'https://open.feishu.cn/open-apis/bot/v2/hook/d48c2e4a-0ef9-4684-88d4-e62d878fdaca';
//测试频道
const url_test = 'https://open.feishu.cn/open-apis/bot/v2/hook/34a9f127-3838-43fc-bc35-6f5e4e96bf6d';
//交易与跟单业务沟通
... ... @@ -24,31 +26,34 @@ class Feishu{
const url_strategy = 'https://open.feishu.cn/open-apis/bot/v2/hook/53444f37-cfec-420c-a4e6-2f415b908dee';
//网格策略运营群
const url_grid = 'https://open.feishu.cn/open-apis/bot/v2/hook/19471aa1-f926-46d7-a1d5-a367d1449092';
static public function notice($content,$channel_url,$users=[])
static public function notice($content, $channel_url, $users = [])
{
$userXml = '';
foreach ($users as $user) {
$userXml .= "<at user_id='" . $user . "'></at>";
}
$content = [
'msg_type'=>"text",
'content'=>[
'text'=>$content.$userXml
'msg_type' => "text",
'content' => [
'text' => $content . $userXml
]
];
$con = json_encode($content);
return self::send_post_json($channel_url,$con);
return self::send_post_json($channel_url, $con);
}
static public function send_post_json($url, $jsonStr)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($jsonStr)
)
... ... @@ -58,4 +63,4 @@ class Feishu{
curl_close($ch);
return array($httpCode, $response);
}
}
\ No newline at end of file
}
... ...
... ... @@ -27,5 +27,4 @@ class KlineAssist
}
return -1;
}
}
\ No newline at end of file
}
... ...
<?php
namespace jytools;
require_once __DIR__ . '/functions.php';
class Logger
{
... ... @@ -8,45 +9,52 @@ class Logger
private bool $dateSlice;
private array $types;
public function __construct($logPath, $types = ['info','warning','error'], $dateSlice = false)
public function __construct($logPath, $types = ['info', 'warning', 'error'], $dateSlice = false)
{
$this->logPath = $logPath;
$this->dateSlice = $dateSlice;
$this->types = $types;
}
public function debug($msg){
$this->log($msg,'debug');
public function debug($msg)
{
$this->log($msg, 'debug');
}
public function info($msg){
$this->log($msg,'info');
public function info($msg)
{
$this->log($msg, 'info');
}
public function warning($msg){
$this->log($msg,'warning');
public function warning($msg)
{
$this->log($msg, 'warning');
}
public function error($msg){
$this->log($msg,'error');
public function error($msg)
{
$this->log($msg, 'error');
}
private function log($msg, $type){
$msg = '['.timeFormat('ms').']['.$type.']:'.$msg.PHP_EOL;
private function log($msg, $type)
{
$msg = '[' . timeFormat('ms') . '][' . $type . ']:' . $msg . PHP_EOL;
echo $msg;
if (!in_array($type,$this->types)){
if (!in_array($type, $this->types)) {
return;
}
if ($this->dateSlice) {
$path = $this->logPath.'/'.date('Y-m-d');
}else{
$path = $this->logPath . '/' . date('Y-m-d');
} else {
$path = $this->logPath;
}
$file = $path.'/'.$type.'.log';
$this->save($file,$msg,$type);
$file = $path . '/' . $type . '.log';
$this->save($file, $msg, $type);
}
private function save($file,$msg, $type='info'){
\Swoole\Coroutine::create(function () use ($file,$msg,$type) {
private function save($file, $msg, $type = 'info')
{
\Swoole\Coroutine::create(function () use ($file, $msg, $type) {
$this->checkFileDir($file);
file_put_contents($file,$msg,FILE_APPEND);
file_put_contents($file, $msg, FILE_APPEND);
});
}
private function checkFileDir($file){
private function checkFileDir($file)
{
// 获取目录路径
$directoryPath = dirname($file);
if (!is_dir($directoryPath)) {
... ... @@ -54,4 +62,4 @@ class Logger
mkdir($directoryPath, 0755, true);
}
}
}
\ No newline at end of file
}
... ...
<?php
namespace jytools;
class MongoCli
{
private $pool;
private $database;
public function __construct($host,$port,$username,$password,$database, $num = 20)
public function __construct($host, $port, $username, $password, $database, $num = 20)
{
$this->database = $database;
$userInfo = $username?"{$username}:{$password}@":"";
$userInfo = $username ? "{$username}:{$password}@" : "";
$dsn = "mongodb://{$userInfo}{$host}:{$port}/{$database}";
$this->pool = new MongoPool($dsn,$num);
$this->pool = new MongoPool($dsn, $num);
}
/*
* 创建集合
*/
public function createCollection($table,$createIndex=[]){
public function createCollection($table, $createIndex = [])
{
try {
$mongodb = $this->pool->get();
$database = $mongodb->selectDatabase($this->database);
... ... @@ -59,7 +61,7 @@ class MongoCli
* 写入数据
* $collection->insertOne(['name' => 'John Doe']);
* */
public function insertOne($table,$data = [])
public function insertOne($table, $data = [])
{
try {
$mongodb = $this->pool->get();
... ... @@ -78,7 +80,7 @@ class MongoCli
* 批量写入数据
* $collection->insertMany([['name' => 'John Doe'],['name' => 'John Doe']]);
* */
public function insertAll($table,$data = [])
public function insertAll($table, $data = [])
{
try {
$mongodb = $this->pool->get();
... ... @@ -97,7 +99,7 @@ class MongoCli
* 查询单条数据
* $collection->findOne(['name' => 'John Doe']);
* */
public function findOne($table,$where = [])
public function findOne($table, $where = [])
{
try {
$mongodb = $this->pool->get();
... ... @@ -124,21 +126,21 @@ class MongoCli
* 'limit' => 100,
* ];
* */
public function findAll($table,$where = [], $options=[])
public function findAll($table, $where = [], $options = [])
{
try {
$mongodb = $this->pool->get();
$database = $mongodb->selectDatabase($this->database);
$collection = $database->selectCollection($table);
$result = $collection->find($where,$options);
$result = $collection->find($where, $options);
$this->pool->push($mongodb);
// 遍历结果集
$data = [];
if ($result){
$arr = $result->toArray();
if ($result) {
$arr = $result->toArray();
foreach ($arr as $item) {
$data[] = $item->getArrayCopy();
}
}
return $data;
}
return [];
... ... @@ -152,13 +154,13 @@ class MongoCli
* 更新数据
* $collection->updateOne(['name' => 'John Doe'], ['$set' => ['age' => 31]]);
* */
public function updateOne($table,$where = [],$upData = [])
public function updateOne($table, $where = [], $upData = [])
{
try {
$mongodb = $this->pool->get();
$database = $mongodb->selectDatabase($this->database);
$collection = $database->selectCollection($table);
$result = $collection->updateOne($where,$upData);
$result = $collection->updateOne($where, $upData);
$this->pool->push($mongodb);
return $result;
} catch (\Exception $e) {
... ... @@ -171,7 +173,7 @@ class MongoCli
* 删除数据
* $collection->deleteOne(['name' => 'John Doe']);
* */
public function deleteOne($table,$where = [])
public function deleteOne($table, $where = [])
{
try {
$mongodb = $this->pool->get();
... ... @@ -190,7 +192,7 @@ class MongoCli
* 批量删除数据
* $collection->deleteMany(['name' => 'John Doe']);
* */
public function deleteBatch($table,$where = [])
public function deleteBatch($table, $where = [])
{
try {
$mongodb = $this->pool->get();
... ... @@ -204,5 +206,4 @@ class MongoCli
return [];
}
}
}
\ No newline at end of file
}
... ...
<?php
namespace jytools;
use MongoDB\Client;
... ... @@ -13,7 +14,7 @@ class MongoPool
private $mongoUri;
private $options;
public function __construct($mongoUri, $maxSize=20, $options = [])
public function __construct($mongoUri, $maxSize = 20, $options = [])
{
$this->mongoUri = $mongoUri;
$this->maxSize = $maxSize;
... ... @@ -35,8 +36,8 @@ class MongoPool
public function get()
{
while ($this->pool->isEmpty()){
// output('Mongodb连接池为空,等待释放连接');
while ($this->pool->isEmpty()) {
// output('Mongodb连接池为空,等待释放连接');
Coroutine::sleep(0.1);
}
$connection = $this->pool->pop();
... ... @@ -58,7 +59,7 @@ class MongoPool
// 检查连接是否有效,这里仅做示例,实际应用中可能需要更复杂的逻辑
if (is_object($connection) && get_class($connection) === Client::class) {
$this->pool->push($connection);
}else{
} else {
$this->currentSize -= 1;
}
}
... ... @@ -73,4 +74,4 @@ class MongoPool
}
$this->currentSize = 0;
}
}
\ No newline at end of file
}
... ...
... ... @@ -9,7 +9,7 @@ class MysqlCli
{
private $pool = null;
private $prefix = '';// 前缀
private $prefix = ''; // 前缀
private int $reconnectCount = 0; //period时间内重连次数
private int $period = 300;
... ... @@ -40,13 +40,13 @@ class MysqlCli
$this->pool->close();
}
$this->pool = new MysqliPool((new MysqliConfig)
->withHost($this->connectConfig['host'])
->withPort($this->connectConfig['port'])
->withDbName($this->connectConfig['database'])
->withCharset($this->connectConfig['charset'])
->withUsername($this->connectConfig['username'])
->withPassword($this->connectConfig['password'])
, $this->connectConfig['connectCount']
->withHost($this->connectConfig['host'])
->withPort($this->connectConfig['port'])
->withDbName($this->connectConfig['database'])
->withCharset($this->connectConfig['charset'])
->withUsername($this->connectConfig['username'])
->withPassword($this->connectConfig['password']),
$this->connectConfig['connectCount']
);
$this->prefix = $this->connectConfig['prefix'];
}
... ... @@ -273,5 +273,4 @@ class MysqlCli
}
return $valueNew;
}
}
\ No newline at end of file
}
... ...
<?php
namespace jytools;
/*
所有接口
*/
class OkApi
{
protected string $host = 'https://www.okx.com';
... ... @@ -78,9 +80,9 @@ class OkApi
]);
}
$headers_array=[];
foreach ($headers as $key => $value){
$headers_array[]=$key.':'.$value;
$headers_array = [];
foreach ($headers as $key => $value) {
$headers_array[] = $key . ':' . $value;
}
$this->headers = $headers_array;
return $headers;
... ... @@ -90,14 +92,14 @@ class OkApi
* 公共请求接口
* $type 1: 需鉴权 2: 不需鉴权
* */
public function request($method, $path, $param,$type=1)
public function request($method, $path, $param, $type = 1)
{
$this->method = strtoupper($method);
$this->path = $path;
$this->param = $param;
if($type==2){
if ($type == 2) {
$this->createHeaders();
}else{
} else {
if (empty($this->apikey) || empty($this->secret) || empty($this->apipwd)) {
return ['code' => -1, 'msg' => 'apikey, secret or apipwd is empty'];
}
... ... @@ -125,7 +127,7 @@ class OkApi
/**
* 合约账户余额查询
*/
public function getBalance($param=[])
public function getBalance($param = [])
{
$path = '/api/v5/account/balance';
return $this->request('GET', $path, $param);
... ... @@ -133,7 +135,7 @@ class OkApi
/**
* 资金账户余额查询
*/
public function getAssetBalance($param=[])
public function getAssetBalance($param = [])
{
$path = '/api/v5/asset/balances';
return $this->request('GET', $path, $param);
... ... @@ -158,10 +160,9 @@ class OkApi
/*
* 公共请求接口
* */
public function getTransferHistory($path,$param)
public function getTransferHistory($path, $param)
{
$path = '/api/v5/asset/bills';
return $this->request('GET', $path, $param);
}
}
... ...
<?php
namespace jytools;
use Swoole\Database\RedisConfig;
... ... @@ -8,21 +9,22 @@ class RedisCli
{
private $pool;
public $subRedis = null;
public function __construct($host,$port,$password,$dbIndex, $num = 20)
public function __construct($host, $port, $password, $dbIndex, $num = 20)
{
$this->pool = new RedisPool((new RedisConfig)
->withHost($host)
->withPort($port)
->withAuth($password)
->withDbIndex($dbIndex)
,$num //默认64个连接池
->withHost($host)
->withPort($port)
->withAuth($password)
->withDbIndex($dbIndex),
$num //默认64个连接池
);
}
//集合存数据
public function sAdd($key,$member){
public function sAdd($key, $member)
{
$redis = $this->pool->get();
try {
$res = $redis->sAdd($key,$member);
$res = $redis->sAdd($key, $member);
} catch (\RedisException $e) {
return false;
}
... ... @@ -31,7 +33,8 @@ class RedisCli
}
//获取集合
public function sMembers($key){
public function sMembers($key)
{
$redis = $this->pool->get();
try {
$res = $redis->sMembers($key);
... ... @@ -43,11 +46,12 @@ class RedisCli
}
//移除集合成员
public function sRem($key,$member){
public function sRem($key, $member)
{
$redis = $this->pool->get();
try {
$res = $redis->sRem($key,$member);
}catch (\RedisException $e){
$res = $redis->sRem($key, $member);
} catch (\RedisException $e) {
return false;
}
... ... @@ -56,7 +60,8 @@ class RedisCli
}
//哈希 键 字段 值 设置
public function hSet($key,$field,$value){
public function hSet($key, $field, $value)
{
$redis = $this->pool->get();
try {
$res = $redis->hSet($key, $field, $value);
... ... @@ -67,7 +72,8 @@ class RedisCli
return $res;
}
//获取 键对应字段的值
public function hGet($key,$field){
public function hGet($key, $field)
{
$redis = $this->pool->get();
try {
$res = $redis->hGet($key, $field);
... ... @@ -78,7 +84,8 @@ class RedisCli
return $res;
}
//获取键所有字段和值
public function hGetAll($key){
public function hGetAll($key)
{
$redis = $this->pool->get();
try {
$res = $redis->hGetAll($key);
... ... @@ -89,7 +96,8 @@ class RedisCli
return $res;
}
//删除一个值
public function hDel($key,$field){
public function hDel($key, $field)
{
$redis = $this->pool->get();
try {
$res = $redis->hDel($key, $field);
... ... @@ -104,7 +112,8 @@ class RedisCli
* 发布订阅等
*/
//将信息发送到指定的频道
public function publish($channel,$message){
public function publish($channel, $message)
{
$redis = $this->pool->get();
try {
$res = $redis->publish($channel, $message);
... ... @@ -115,13 +124,13 @@ class RedisCli
return $res;
}
public function subscribe($channels,callable $onMessage)
public function subscribe($channels, callable $onMessage)
{
$redis = $this->pool->get();
$this->subRedis = $redis;
try {
$res = $redis->subscribe($channels,function($redis, $channel, $message)use($onMessage){
call_user_func($onMessage,$redis, $channel, $message);
$res = $redis->subscribe($channels, function ($redis, $channel, $message) use ($onMessage) {
call_user_func($onMessage, $redis, $channel, $message);
});
} catch (\RedisException $e) {
return false;
... ... @@ -131,20 +140,19 @@ class RedisCli
return $res;
}
public function psubscribe($channels,callable $onMessage)
public function psubscribe($channels, callable $onMessage)
{
$redis = $this->pool->get();
$this->subRedis = $redis;
try {
$res = $redis->psubscribe($channels,function($redis, $pattern, $channel, $message)use($onMessage){
$res = $redis->psubscribe($channels, function ($redis, $pattern, $channel, $message) use ($onMessage) {
call_user_func($onMessage, $pattern, $redis, $channel, $message);
});
}catch (\RedisException $e) {
} catch (\RedisException $e) {
return false;
}
$this->subRedis = null;
$this->pool->put($redis);
return $res;
}
}
\ No newline at end of file
}
... ...
... ... @@ -22,4 +22,4 @@ class SimpleRequest
$this->header = $data['header'];
$this->cookie = $data['cookie'];
}
}
\ No newline at end of file
}
... ...
<?php
namespace jytools;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;
... ... @@ -11,8 +13,9 @@ class SimpleServer
{
$this->httpServer = new Server($host, $port);
}
public function router($url, $callback){
$this->httpServer->on('Request', function (Request $request, Response $response) use ($url, $callback){
public function router($url, $callback)
{
$this->httpServer->on('Request', function (Request $request, Response $response) use ($url, $callback) {
$requestInfo = [
'path' => $request->server['path_info'],
'uri' => $request->server['request_uri'],
... ... @@ -27,11 +30,11 @@ class SimpleServer
$response->end();
return;
}
if($url == $simpleRequest->uri){
if ($url == $simpleRequest->uri) {
$res = call_user_func($callback, $simpleRequest);
if(!$res){
if (!$res) {
$response->end();
}else{
} else {
$response->end($res);
}
return;
... ... @@ -40,8 +43,8 @@ class SimpleServer
});
}
public function start(){
public function start()
{
$this->httpServer->start();
}
}
... ...
<?php
namespace jytools;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Coroutine\Http\Server;
... ... @@ -11,10 +13,11 @@ class SimpleServerCoroutine
{
$this->httpServer = new Server($host, $port, $ssl);
}
public function router($method, $path, $callback){
$this->httpServer->handle($path, function (Request $request, Response $response) use ($method,$callback) {
public function router($method, $path, $callback)
{
$this->httpServer->handle($path, function (Request $request, Response $response) use ($method, $callback) {
$m = $request->getMethod();
if(!in_array($m,$method)){
if (!in_array($m, $method)) {
$response->status(405);
$response->end();
return;
... ... @@ -30,16 +33,16 @@ class SimpleServerCoroutine
];
$simpleRequest = new SimpleRequest($requestInfo);
$res = call_user_func($callback, $simpleRequest);
if(empty($res)){
$response->end(json_encode(['code'=>-1,'msg'=>'nothing return']));
}else{
if (empty($res)) {
$response->end(json_encode(['code' => -1, 'msg' => 'nothing return']));
} else {
$response->end($res);
}
});
}
public function start(){
public function start()
{
$this->httpServer->start();
}
}
... ...
<?php
namespace jytools;
//格式化输出
use Swoole\Process;
... ... @@ -7,25 +8,25 @@ use Swoole\Event;
function output(): void
{
$args = func_get_args();
$outStr = '['.timeFormat('ms').']:';
foreach($args as $key => $value){
$outStr = '[' . timeFormat('ms') . ']:';
foreach ($args as $key => $value) {
$value = is_array($value) ? json_encode($value) : $value;
if(is_bool($value)){
$value = $value ? 'bool:true':'bool:false';
if (is_bool($value)) {
$value = $value ? 'bool:true' : 'bool:false';
}
$outStr .= count($args) - $key > 1 ? $value.' ' : $value;
$outStr .= count($args) - $key > 1 ? $value . ' ' : $value;
}
echo $outStr.PHP_EOL;
echo $outStr . PHP_EOL;
}
//格式化时间
function timeFormat($type='s',$format='Y-m-d H:i:s'): string
function timeFormat($type = 's', $format = 'Y-m-d H:i:s'): string
{
date_default_timezone_set('Asia/Shanghai');
$microTime = microtime();
list($msTime,$sTime) = explode(' ',$microTime);
$timeStr = date($format,$sTime);
if($type == 'ms'){
$timeStr .= '.'.sprintf("%03d",floor($msTime*1000));
list($msTime, $sTime) = explode(' ', $microTime);
$timeStr = date($format, $sTime);
if ($type == 'ms') {
$timeStr .= '.' . sprintf("%03d", floor($msTime * 1000));
}
return $timeStr;
}
... ... @@ -34,55 +35,88 @@ function timeFormat($type='s',$format='Y-m-d H:i:s'): string
function getMicrotime(): float|int
{
list($uSec, $sec) = explode(' ', microtime());
return $sec*1000+round($uSec*1000);
return $sec * 1000 + round($uSec * 1000);
}
//获取精度
function getPrecision($number): int
{
$count = 0;
while($number < 1){
while ($number < 1) {
$number *= 10;
$count += 1;
}
return $count;
}
function getIntervalUnit($interval,$type='s'): float|int
function getIntervalUnit($interval, $type = 's'): float|int
{
$unitTime = 0;
if($interval == '1m'){
if ($interval == '1m') {
$unitTime = 60;
}
if($interval == '5m'){
$unitTime = 60*5;
if ($interval == '5m') {
$unitTime = 60 * 5;
}
if ($interval == '15m') {
$unitTime = 60 * 15;
}
if ($interval == '1h') {
$unitTime = 60 * 60;
}
if($interval == '15m'){
$unitTime = 60*15;
if ($interval == '4h') {
$unitTime = 60 * 60 * 4;
}
if($interval == '1h'){
$unitTime = 60*60;
if ($interval == '1d') {
$unitTime = 60 * 60 * 24;
}
return $type == 's' ? $unitTime : $unitTime * 1000;
}
//科学计数法转数字
function scToNum($scStr)
{
$check_str = '';
if (strpos($scStr, 'e') !== false) {
$check_str = 'e';
}
if($interval == '4h'){
$unitTime = 60*60*4;
if (strpos($scStr, 'E') !== false) {
$check_str = 'E';
}
if($interval == '1d'){
$unitTime = 60*60*24;
if (empty($check_str)) {
return $scStr; //非科学计数直接返回。
}
return $type == 's' ? $unitTime : $unitTime*1000;
$num_length = 0;
$split_array = explode($check_str, $scStr);
$num_length += strlen($split_array[0]);
$num_length += (int)str_replace(['-', '+'], '', $split_array[1]);
$float_number = (float)$scStr;
$decimal_string = number_format($float_number, $num_length, '.', '');
$num = rtrim(rtrim($decimal_string, '0'), '.'); //去除小数后多余的0
return $num;
}
//时间戳转ISO8601
function tsToISO($timestamp)
{
$datetime = new \DateTime();
$datetime->setTimestamp(floor($timestamp / 1000));
$datetime->setTimezone(new \DateTimeZone('UTC'));
$milliseconds = sprintf('.%03d', $timestamp % 1000);
return $datetime->format('Y-m-d\TH:i:s') . $milliseconds . 'Z';
}
//以守护进程运行
function runAsDaemon($callback,$isDaemon=true): void
function runAsDaemon($callback, $isDaemon = true): void
{
if($isDaemon){
if ($isDaemon) {
Process::daemon();
$process = new Process(function ()use ($callback){
$process = new Process(function () use ($callback) {
call_user_func($callback);
Event::wait();
});
$process->start();
}else{
} else {
call_user_func($callback);
Event::wait();
}
... ...
<?php
require_once __DIR__ . '/Auth.php';
require_once __DIR__ . '/BinanceFutures.php';
require_once __DIR__ . '/BinanceSpot.php';
require_once __DIR__ . '/Curl.php';
require_once __DIR__ . '/FeiShu.php';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/KlineAssist.php';
require_once __DIR__ . '/Logger.php';
require_once __DIR__ . '/MongoCli.php';
require_once __DIR__ . '/MongoPool.php';
require_once __DIR__ . '/MysqlCli.php';
require_once __DIR__ . '/OkApi.php';
require_once __DIR__ . '/RedisCli.php';
require_once __DIR__ . '/SimpleRequest.php';
require_once __DIR__ . '/SimpleServer.php';
require_once __DIR__ . '/SimpleServerCoroutine.php';
require_once __DIR__ . '/Websocket.php';
... ...
... ... @@ -2,8 +2,7 @@
namespace trader;
require_once __DIR__ . '/autoload.php';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/load.php';
use trader\struct\ApiInfo;
use trader\okx\ExBroker as OkxBroker;
... ... @@ -17,7 +16,7 @@ use trader\struct\SymbolInfo;
use trader\struct\WsDataOrder;
use trader\struct\Pos;
use \Exception;
use function Jiaoyin\timeFormat;
use function jytools\timeFormat;
use trader\okx\Api as OkApi;
class CmBroker
... ...
<?php
namespace trader;
function scToNum($scStr)
{
$check_str = '';
if (strpos($scStr, 'e') !== false) {
$check_str = 'e';
}
if (strpos($scStr, 'E') !== false) {
$check_str = 'E';
}
if (empty($check_str)) {
return $scStr; //非科学计数直接返回。
}
$num_length = 0;
$split_array = explode($check_str, $scStr);
$num_length += strlen($split_array[0]);
$num_length += (int)str_replace(['-', '+'], '', $split_array[1]);
$float_number = (float)$scStr;
$decimal_string = number_format($float_number, $num_length, '.', '');
$num = rtrim(rtrim($decimal_string, '0'), '.'); //去除小数后多余的0
return $num;
}
function tsToISO($timestamp)
{
$datetime = new \DateTime();
$datetime->setTimestamp(floor($timestamp / 1000));
$datetime->setTimezone(new \DateTimeZone('UTC'));
$milliseconds = sprintf('.%03d', $timestamp % 1000);
return $datetime->format('Y-m-d\TH:i:s') . $milliseconds . 'Z';
}
... ... @@ -2,12 +2,12 @@
namespace trader\binance;
require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/../../load.php';
require_once __DIR__ . '/Api.php';
use trader\struct\ApiInfo;
use trader\binance\Api as BnApi;
use Jiaoyin\Websocket;
use jytools\Websocket;
class ExBroker
{
... ... @@ -28,7 +28,8 @@ class ExBroker
}
//获取所有品种资金费率
public function getAllPremium() {
public function getAllPremium()
{
$res = $this->api->getPremiumIndex();
}
}
... ...
... ... @@ -6,9 +6,9 @@ require_once __DIR__ . '/../../autoload.php';
require_once __DIR__ . '/../../../vendor/autoload.php';
use trader\struct\ApiInfo;
use Jiaoyin\Curl;
use function Jiaoyin\getMicrotime;
use function trader\tsToISO;
use jytools\Curl;
use function jytools\getMicrotime;
use function jytools\tsToISO;
class Api
{
... ...
... ... @@ -2,13 +2,13 @@
namespace trader\okx;
require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/../../load.php';
require_once __DIR__ . '/Api.php';
use trader\struct\ApiInfo;
use trader\okx\Api as OkxApi;
use Jiaoyin\Websocket;
use function Jiaoyin\output;
use jytools\Websocket;
use function jytools\output;
class ExBroker
... ...
<?php
require_once __DIR__ . '/../jytools/load.php';
require_once __DIR__ . '/CmBroker.php';
require_once __DIR__ . '/common/tool.php';
require_once __DIR__ . '/struct/ApiInfo.php';
require_once __DIR__ . '/struct/SymbolInfo.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/WsDataOrder.php';
require_once __DIR__ . '/struct/Pos.php';
require_once __DIR__ . '/struct/Kline.php';
require_once __DIR__ . '/exchange/okx/ExBroker.php';
require_once __DIR__ . '/exchange/binance/ExBroker.php';
... ...
... ... @@ -4,7 +4,7 @@ namespace trader\struct;
require_once __DIR__ . '/../../vendor/autoload.php';
use function Jiaoyin\getPrecision;
use function jytools\getPrecision;
class SymbolInfo
{
... ...