PHP code example of ragingprodigy / alpaca-php

1. Go to this page and download the library: Download ragingprodigy/alpaca-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ragingprodigy / alpaca-php example snippets


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/'));
    
$account = $client->getAccount(); // Returns an instance of "Ragingprodigy\Alpaca\Entities\Account"
$orders = $client->getOrders(); // Returns an array of "Ragingprodigy\Alpaca\Entities\Order" instances

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";
}

$client->getAccount(); //Account

$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

$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[]

$client->getOrder(string $orderId); // Order

$client->getOrderByClientOrderId(string $clientOrderId); // Order

$client->cacnelOrder(string $orderId); // void

$client->getOpenPosition(string $symbol); // Position

$client->getOpenPositions(); // Position[]

$client->getAssets(
    string $status = '' // '', AssetStatus::ACTIVE, AssetStatus::INACTIVE
); // Asset[]

$client->getAsset(string $assetIdOrSymbol); // Asset

$client->getCalendar(DateTime $start = null, DateTime $end = null); // Calendar[]

$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[]