ragingprodigy / alpaca-php
PHP版的Alpaca Trade API客户端
Requires
- php: ^7.2
- ext-json: *
- guzzlehttp/guzzle: ^6.3
- ratchet/pawl: ^0.3.4
Requires (Dev)
- fzaninotto/faker: ^1.8
- phpunit/phpunit: ^8.2
This package is auto-updated.
Last update: 2024-09-19 22:25:13 UTC
README
概述
这是Alpaca(Alpaca网站)的PHP客户端(Alpaca通用API文档)。Alpaca API允许您免费构建和使用实时市场数据。
目录
安装
可以通过Composer安装此包。
composer require ragingprodigy/alpaca-php
基本用法
要使用此库,只需创建一个客户端实例,如下所示
use RagingProdigy\Alpaca\Client; use RagingProdigy\Alpaca\Config; // Paper Trading Client $client = new Client(new Config('apiKey', 'secretKey')); // Live Trading Client $client = new Client(new Config('apiKey', 'secretKey', false)); // Overriding Trading and Data Api URLs $client = new Client(new Config('apiKey', 'secretKey', true, 'https://trading.url/v2/', 'https://data.url/v1/'));
在底层,该库使用Guzzle Http客户端库发送HTTP请求。您也可以通过将自定义ClientInterface作为第二个参数传递给Client构造函数来进一步自定义GuzzleHttp客户端。
然后您可以通过调用以下方式访问可用的API
$account = $client->getAccount(); // Returns an instance of "Ragingprodigy\Alpaca\Entities\Account" $orders = $client->getOrders(); // Returns an array of "Ragingprodigy\Alpaca\Entities\Order" instances
完整示例
以下是使用此库打印账户信息、提交限价订单和打印bars的方法。
use RagingProdigy\Alpaca\Client; use RagingProdigy\Alpaca\Config; use RagingProdigy\Alpaca\Constants\BarTimeFrame; use RagingProdigy\Alpaca\Constants\DataStream; use RagingProdigy\Alpaca\Constants\OrderAction; use RagingProdigy\Alpaca\Constants\OrderType; use RagingProdigy\Alpaca\Constants\TimeInForce; use RagingProdigy\Alpaca\Entities\AccountUpdateEvent; use RagingProdigy\Alpaca\Entities\OrderUpdateEvent; use RagingProdigy\Alpaca\Entities\UpdateEvent; use Ratchet\Client\WebSocket; $alpacaClient = new Client(new Config('api.key', 'secret.key')); // Listen for Updates $alpacaClient->connectToStreams([DataStream::ACCOUNT_UPDATES, DataStream::TRADE_UPDATES], static function (WebSocket $webSocket, UpdateEvent $event = null) { if ($event instanceof OrderUpdateEvent) { echo "Order Update Event Received: $event\n"; } if ($event instanceof AccountUpdateEvent) { echo "Account Update Event Received: $event\n"; } }); // Get Account Info $account = $alpacaClient->getAccount(); echo "\nAccount Information: \n"; echo "\tCreated At: {$account->getCreatedAt()}\n"; echo "\tBuying Power: $ {$account->getBuyingPower()}\n"; echo "\tPortfolio Value: $ {$account->getPortfolioValue()}\n\n"; // Get Market Clock $clock = $alpacaClient->getClock(); echo "Clock: \n"; echo "\tCurrent Time: {$clock->getTimestamp()}\n"; echo "\tMarket Next Open Time: {$clock->getNextOpen()}\n"; echo "\tMarket Next Close Time: {$clock->getNextClose()}\n\n"; // Request Purchase Order $order = $alpacaClient->requestNewOrder( 'AAPL', 5, OrderAction::BUY, OrderType::MARKET, TimeInForce::DAY ); echo "Market Order Response: \n"; echo "\tSymbol: {$order->getSymbol()}\n"; echo "\tClient Order Id: {$order->getClientOrderId()}\n"; echo "\tQuantity: {$order->getQuantity()}\n"; echo "\tType: {$order->getType()}\n"; echo "\tCreated At: {$order->getCreatedAt()}\n\n"; // Find Order By ID $marketOrder = $alpacaClient->getOrder($order->getId()); echo "Market Order by ID Response: \n"; echo "\tSymbol: {$marketOrder->getSymbol()}\n"; echo "\tClient Order Id: {$marketOrder->getClientOrderId()}\n"; echo "\tQuantity: {$marketOrder->getQuantity()}\n"; echo "\tType: {$marketOrder->getType()}\n"; echo "\tCreated At: {$marketOrder->getCreatedAt()}\n\n"; // Find Order By Client Order ID $orderByClientOrderId = $alpacaClient->getOrderByClientOrderId($order->getClientOrderId()); echo "Market Order by ID Response: \n"; echo "\tSymbol: {$orderByClientOrderId->getSymbol()}\n"; echo "\tClient Order Id: {$orderByClientOrderId->getClientOrderId()}\n"; echo "\tQuantity: {$orderByClientOrderId->getQuantity()}\n"; echo "\tType: {$orderByClientOrderId->getType()}\n"; echo "\tCreated At: {$orderByClientOrderId->getCreatedAt()}\n\n"; // Cancel Order $alpacaClient->cancelOrder($order->getId()); // Would raise an exception if not successful // Get Bars $bars = $alpacaClient->getBars(['AMZN'], BarTimeFrame::DAY, 4); echo "Bars Response: \n"; foreach ($bars as $bar) { echo "\t========================\n"; echo "\tSymbol: {$bar->getSymbol()}\n"; echo "\tOpen: {$bar->getO()}\n"; echo "\tHigh: {$bar->getH()}\n"; echo "\tLow: {$bar->getL()}\n"; echo "\tClose: {$bar->getC()}\n"; echo "\tVolume: {$bar->getV()}\n"; }
上述代码的输出类似如下
Account Information:
Created At: 2019-06-26T15:19:01.819453Z
Buying Power: $ 398861.06
Portfolio Value: $ 100003.99
Clock:
Current Time: 2019-07-01T03:14:37.582893836-04:00
Market Next Open Time: 2019-07-01T09:30:00-04:00
Market Next Close Time: 2019-07-01T16:00:00-04:00
Market Order Response:
Symbol: AAPL
Client Order Id: 309626b7-5569-4ae5-bb16-d93930b8b82b
Quantity: 5
Type: market
Created At: 2019-07-01T07:14:39.022538874Z
Order Update Event: {"event":"new","order":{"asset_class":"us_equity","asset_id":"b0b6dd9d-8b9b-48a9-ba46-b9d54906e415","canceled_at":null,"client_order_id":"abea2d0b-2340-4034-a50c-b4f09cde1e0b","created_at":"2019-07-01T07:12:16.177026Z","expired_at":null,"failed_at":null,"filled_at":null,"filled_avg_price":null,"filled_qty":"0","id":"b3332b17-b7dc-4a55-9a3c-dfd0c50ecc62","limit_price":null,"order_type":"market","qty":"5","side":"buy","status":"new","stop_price":null,"submitted_at":"2019-07-01T07:12:16.165806Z","symbol":"AAPL","time_in_force":"day","type":"market","updated_at":"2019-07-01T07:12:20.373783079Z"}}
Market Order by ID Response:
Symbol: AAPL
Client Order Id: 309626b7-5569-4ae5-bb16-d93930b8b82b
Quantity: 5
Type: market
Created At: 2019-07-01T07:14:39.022539Z
Market Order by ID Response:
Symbol: AAPL
Client Order Id: 309626b7-5569-4ae5-bb16-d93930b8b82b
Quantity: 5
Type: market
Created At: 2019-07-01T07:14:39.022539Z
Order Update Event: {"event":"canceled","order":{"asset_class":"us_equity","asset_id":"b0b6dd9d-8b9b-48a9-ba46-b9d54906e415","canceled_at":"2019-07-01T07:12:20.369944583Z","client_order_id":"abea2d0b-2340-4034-a50c-b4f09cde1e0b","created_at":"2019-07-01T07:12:16.177026Z","expired_at":null,"failed_at":null,"filled_at":null,"filled_avg_price":null,"filled_qty":"0","id":"b3332b17-b7dc-4a55-9a3c-dfd0c50ecc62","limit_price":null,"order_type":"market","qty":"5","side":"buy","status":"canceled","stop_price":null,"submitted_at":"2019-07-01T07:12:16.165806Z","symbol":"AAPL","time_in_force":"day","type":"market","updated_at":"2019-07-01T07:12:20.384272245Z"},"timestamp":"2019-07-01T07:12:20.369944583Z"}
Bars Response:
========================
Symbol: AAPL
Open: 198.43
High: 199.26
Low: 195.29
Close: 195.57
Volume: 18361798
========================
Symbol: AAPL
Open: 197.83
High: 200.99
Low: 197.35
Close: 199.8
Volume: 22499633
========================
Symbol: AAPL
Open: 200.29
High: 201.57
Low: 199.57
Close: 199.73
Volume: 15460769
========================
Symbol: AAPL
Open: 199.24
High: 199.4
Low: 197.05
Close: 197.92
Volume: 18773228
方法
所有API方法都在Alpaca客户端(RagingProdigy\Alpaca\Client)上可用。
账户API
调用 GET /account
并返回当前账户
$client->getAccount(); //Account
订单API
请求新订单
调用 POST /orders
并创建新订单。
$client->requestNewOrder( string $symbol, int $quantity, string $action, // OrderAction::BUY, OrderAction::SELL string $type, // OrderType::MARKET, OrderType::STOP, OrderType::LIMIT, OrderType::STOP_LIMIT, string $timeInForce, // TimeInForce::DAY, TimeInForce::GTC, TimeInForce::OPG, TimeInForce::IOC, TimeInForce::FOK float $limitPrice = null, float $stopPrice = null, bool $extendedHours = false, $clientOrderId = null ); // Order
获取订单
调用 GET /orders
并返回一个Order对象数组。
$client->getOrders( string $status = OrderStatus::OPEN, // OrderStatus::CLOSED, OrderStatus::OPEN, OrderStatus::ALL int $limit = 50, DateTime $after = null, DateTime $until = null, string $direction = Sorting::DESCENDING // Sorting::ASCENDING, Sorting::DESCENDING ); // Order[]
通过ID获取订单
调用 GET /orders/{id}
并返回一个Order。
$client->getOrder(string $orderId); // Order
通过客户订单ID获取订单
调用 GET /orders:by_client_order_id
并返回一个按client_order_id
获取的订单。您可以在创建订单时设置client_order_id
,以便轻松跟踪您的订单。
$client->getOrderByClientOrderId(string $clientOrderId); // Order
取消订单
调用 DELETE /orders/{id}
并删除订单。
$client->cacnelOrder(string $orderId); // void
当失败时引发AlpacaApiException
。
持仓API
获取持仓
调用 GET /positions/{symbol}
并返回一个Position。
$client->getOpenPosition(string $symbol); // Position
获取所有持仓
调用 GET /positions
并返回一个Position对象数组。
$client->getOpenPositions(); // Position[]
资产API
获取资产
调用 GET /assets/
并返回符合您条件的资产数组。
$client->getAssets( string $status = '' // '', AssetStatus::ACTIVE, AssetStatus::INACTIVE ); // Asset[]
获取资产信息
调用 GET /assets/{symbol}
并返回资产实体。
$client->getAsset(string $assetIdOrSymbol); // Asset
日历API
调用 GET/calendar
并返回选定日期的市场日历。
$client->getCalendar(DateTime $start = null, DateTime $end = null); // Calendar[]
数据API
获取K线
$client->getBars( array $symbols, // up to 200 symbols string $timeFrame, // BarTimeFrame::MINUTE, BarTimeFrame::FIVE_MINUTES, BarTimeFrame::FIFTEEN_MINUTES, BarTimeFrame::DAY int $limit = 100, DateTime $start = null, DateTime $end = null ); // Bar[]
测试
要运行测试,请安装开发依赖项(composer install --dev
),然后运行
vendor/bin/phpunit -c phpunit.xml.dist