Alpaca was built for developers & traders. It can be integrated into any application, no matter the codebase, including PHP. That’s what we’re gonna do in this article, integrate a PHP stock market API (PHP SDK) with Alpaca.
Download the PHP Stock Market API (PHP SDK)PHP Stock Market API, easy-to-use PHP SDK
Get stock market prices, trade with algorithms, connect with apps and build fully-featured stock market services — all with commission-free trading, using the Alpaca API and Jeffrey Hyer’s Alpaca PHP SDK. It’s simple to use & its easy-to-understand documentation allows developers to quickly build apps using PHP. Let’s get started.
Installing the Stock Market PHP SDK
Get started with the PHP stock market API by installing it with composer:
composer require jeffreyhyer/alpaca-trade-api-php
Minimum PHP version notice: This package currently requires PHP >= 7.2.5
Setting up & authorizing the PHP Stock Market API
With just a couple of lines of code, the PHP stock market API will be up and running allowing to use its methods to grab market prices, account information, place orders, and more.
In your PHP application, load the vendor autoload.php
file:
<?php
/**
* Include the required composer packages
*/
require './vendor/autoload.php';
use Alpaca\Alpaca;
// Initialize with your Alpaca API key & secret
$alpaca = new Alpaca( "ALPACA_API_KEY", "ALPACA_API_SECRET" );
What about OAuth?
From v2.1.0
the Alpaca PHP SDK package supports authenticating users via OAuth to the Alpaca API. For a detailed explanation of the OAuth flow, see the Alpaca Docs.
getOauthAuthorizeUrl($client_id, $redirect_uri, $scope = "", $state = null)
Provide your applications $client_id
and your authorized/whitelisted $redirect_uri as well as the desired $scope
and a random $state
value.
This function below will return the URL to which you should redirect your user to in order to authorize your application to access the account:
getOauthAccessToken($code, $client_id, $client_secret, $redirect_uri)
Once the user has authorized your application to access their account, Alpaca will redirect the user back to your $redirect_uri
. In the URL will be a code
parameter, pass that as the $code
parameter to this function along with your $client_id
and $client_secret
and your original $redirect_url
. This function will return an access token that can then be used to call the Alpaca API on behalf of that user/account.
To start using the access token call setAccessToken($token)
with the value of the token.
Once authenticated, you can call getOauthAccessTokenDetails()
to get the details of the access token (status, validity, etc).
Using the PHP stock market API
Initializing and accessing the PHP SDK methods is a cinch. To get started, initialize, the Alpaca
class with your Alpaca API key and secret. You can also set the third parameter to enable or disable paper trading. The default is true
to enable calling against the paper trading endpoint.
use Alpaca\Alpaca;
$alpaca = new Alpaca("KEY", "SECRET", true);
// This call will now work as expected if your KEY and SECRET are valid.
// If not, the response will contain an error explaining what went wrong.
$resp = $alpaca->getAccount();
You can change these values after initialization if necessary using the following methods:
setKey($key)
– Set your Alpaca API keysetSecret($secret)
– Set your Alpaca API secretsetPaper(true)
– Enable or disable paper trading,true
for paper trading,false
for live trading.
Stock market PHP SDK responses
All methods return an instance of the \Alpaca\Response
class which has a number of convenient methods for working with the API response.
getCode()
– Returns the HTTP status code of the request (e.g.200
,403
, etc).getReason()
– Returns the HTTP status reason of the request (e.g.OK
,Forbidden
, etc).getResponse()
– Returns the JSON decoded response.
Here’s an example of a successful call using the getAccount
method:
print_r($alpaca->getAccount()->getResponse());
/*
Returned result:
stdClass Object
(
[id] => null
[status] => ACTIVE
[currency] => USD
[buying_power] => 25000
[cash] => 25000
[cash_withdrawable] => 0
[portfolio_value] => 25000
[pattern_day_trader] =>
[trading_blocked] =>
[transfers_blocked] =>
[account_blocked] =>
[created_at] => 2018-11-01T18:41:35.990779Z
[trade_suspended_by_user] =>
)
*/
Alpaca PHP SDK methods
The PHP stock market API provides several methods allowing you to easily interact with Alpha, grab market data, and even place trades.
Account API
The account API serves important information related to an account, including account status, funds available for trade, funds available for withdrawal, and various flags relevant to an account’s ability to trade.
Get a user’s account data with the getAccount
method:
$alpaca->getAccount()->getResponse();
Orders API
The Orders API allows a user to monitor, place, and cancel their orders with Alpaca. The available stock market API orders methods are listed below:
getOrders($status = null, $limit = null, $after = null, $until = null, $direction = null, $nested = null)
This method retrieves a list of orders for the account, optionally filtered by the supplied query parameters.
createOrder($symbol, $qty, $side, $type, $time_in_force, $limit_price = null, $stop_price = null, $client_order_id = null, $extended_hours = null, $order_class = null, $additional = [])
The createOrder
method places a new order for the given account. An order request may be rejected if the account is not authorized for trading, or if the tradable balance is insufficient to fill the order.
getOrder($order_id)
getOrder
retrieves a single order for the given $order_id
.
getOrderByClientId($client_order_id)
The getOrderByClientId
retrieves a single order for the given $client_order_id
.
replaceOrder($order_id, $qty, $time_in_force, $limit_price = null, $stop_price = null, $client_order_id = null)
replaceOrder
replaces a single order with updated parameters. Each parameter overrides the corresponding attribute of the existing order. The other attributes remain the same as the existing order.
cancelOrder($order_id)
The cancelOrder
method attempts to cancel an open order. If the order is no longer cancelable (example: status=order_filled
), the server will respond with status 422, and reject the request.
cancelAllOrders()
cancelAllOrders
attempts to cancel all open orders. A response will be provided for each order that is attempted to be canceled. If an order is no longer cancelable, the server will respond with status 500 and reject the request.
28 comments on “PHP Stock Market API — a PHP SDK.”.
# Jun 22, 2020
Not to hijack the good work that Ben has done here, but here’s another one that is a bit more dynamic: https://www.newtonanalytics.com/docs/api/stockbeta.php
# Jul 31, 2017
please, i dont know how to make this code function on an interface. somebody help…
# Jul 9, 2017
Yahoo finance API is not available anymore. I have moved to MarketXLS after this change, much more reliable data.
# Jul 31, 2017
please how could i make this codes function so i could view the interface
# Nov 11, 2017
Are you using MarketXLS (w/Excel) or MarketXLS-API (with your own script). If "your own script" what language did you use? I’m going to start work on a php script.
# Dec 12, 2017
PHP, but the place I was pulling data from (Yahoo) no longer provides access to it.
# Jun 9, 2017
The fix for the change in the API can be found here:
https://github.com/scheb/yahoo-finance-api/issues/8#issuecomment-303094304
# Jul 31, 2017
i wanna make this codes work, how could i achieve that.
# Jun 9, 2017
Hello, Yahoo has changed API Query, could you perhaps adopt script? Thanks.
# May 30, 2017
I’ve been using this API as the backbone to a personal project to gather stock information and it has worked flawlessly up until this weekend. Worked correctly last on May 26th, 2017.
I have made no changes to my projects code in several months and have had no issues until this weekend and now the API is unable to retrieve data?
Curious if it is still working for others or if Yahoo finally changed their output methods or blocked this type of data requesting? Any information would be helpful, thanks
# Nov 30, 2016
Great work. This code provides much useful information about stocks.
# Aug 28, 2016
Hi Ben, thanks for this! Working great for me. I can’t seem to find any documentation on changing the interval from "daily" (as you have it) to, say, hourly, or minutes. I’m trying to get the current, or previous day’s intraday data for a stock.
Thanks!
# Jul 16, 2016
Still have the problem with Start/ End Date when using historical data. If I set for symbol = ‘AAPL’:
$start = ’01-01-2013′;
$end = ’31-12-2013′;
I get historical data from 01-01-2013 until now, which is 16-07-2016….Did not find a way to fix this….:-(
Another question:
Is there any way of using this API not only for historical stock, but also for historical currency quotes like ‘EURUSD=X’ or commodities like ‘NG=F’ which would be natural gas. See list of commodities/ currencies at yahoo:
http://finance.yahoo.com/commodities?ltr=1
http://finance.yahoo.com/currencies?ltr=1
That would really be a big thing….I really would appreciate using this API like that. 🙂
Thanks for support and help.
Fred
# May 18, 2016
Since Yahoo Finance told us that they will drop the realtime update for the gold price, is it possible to use Kitco for source instead?
I don’t know is it possible to use it with this API without huge modification.
Regards
# May 18, 2016
Looks like there’s already a script for Kitco: https://gold-feed.com/xml-or-json/tag/kitco-gold-price-live/
# May 18, 2016
That might Gold Feed script could be old information… It looks like they’re trying to sell a service now and finding the actual script is eluding me. I recommend the XML Charts free (or paid) service, providing you follow their terms of use. They provide precious and industrial metal feeds in several currencies.
# May 18, 2016
Link to XMLFeeds: http://www.xmlcharts.com/terms-of-service.html
# Apr 26, 2016
great work man! thanks for sharing, really made my life easier..
# Apr 22, 2016
thanks ben, it work for me.
# Jan 8, 2015
This really works fine!
# Nov 8, 2014
Hey Ben,
This is pretty cool but when I try to save the historical data into a variable; ie: $myhistoricaldata = $StockMarketAPI->getData(), the whole array get printed to the page rather than being saved to my variable. I’m not sure what’s going on.
My code would be as follows:
// Get daily historical data for AAPL
$StockMarketAPI = new StockMarketAPI;
$StockMarketAPI->symbol = 'AAPL';
$StockMarketAPI->history = array(
'start' => '2013-1-1', // yyyy-m-d
'end' => '2013-12-31', // yyyy-m-d
'interval' => 'w' // weekly
);
$myhistoricaldata = $StockMarketAPI->getData());
Any thoughts? Thanks.
# Nov 8, 2014
Oops, there’s an extra bracket at the end of my code example.
# Nov 5, 2014
Great article and thank you for putting this together.
I forked and made a modification to your source so that the getData function will take an array. On GitHub here: https://github.com/d3vit/php-stock-market-api
Feel free to integrate if you’d like.
# Nov 17, 2014
If you submit a pull request, I’ll be happy to integrate the features you add instead of branching off a new one.
# Jul 31, 2017
will it function automatically using the github software?
# Nov 3, 2014
The code actually is broken currently when I attempt to run it. Quick fix is to move
$start = '2013-1-1';
$end = '2013-12-31';
into the actual
# Nov 18, 2014
Thanks for the feedback. Just released a new version (1.3, thanks to @d3vit) that should work better for you. Let me know if you run into any problems.
# Jul 21, 2014
Those codes are real life saver specifically for brokers who usually "misplace" their datas. Thanks Ben!
All comments posted on 'PHP Stock Market API — a PHP SDK.' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.
You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.
Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.