PHP Code Example

Am I able to use Alpaca API to make a trade from a PHP page on a web server?

I only see tutorials and full code example for Python which I do not use. Does anyone have a full code example for Javascript using PHP and a web server?

For example I want to be able to go to a URL like this to issue a limit order: https://www.myswebsite.com/createlimitorder.php?stock=AAPL&type=buy&quantity=10&password=mypassword

So when I hit that URL using my password for security, it would create a limit buy order for Apple for 10 shares.

I only need ONE full code example and I can customize and configure the rest but I have been searching for days now and asking the community in Slack and no one has responded.

-Chris

you need php 7 and guzzle. i have it set up in the www/stock_market/api if you look at GMS Auto Trade V2 is here!
theres a file called alpaca.php
this is what i did to do limit orders, let me know if you need anything!

`<?php
//kris galante krisgcell@gmail.com
//include(‘c:/php/WWW/Stock_Market/config.php’);

set_time_limit ( 30 );

ini_set(‘display_errors’, ‘0’);

ini_set(‘log_errors’, ‘0’);

require ‘./vendor/autoload.php’;

require ‘./src/Alpaca.php’;
require ‘./src/Response.php’;
use Alpaca\Alpaca;

	$ACC_SETING = "C:/php/www/Stock_Market/API/ALPACA_TYPE.DATA"; // I was running the code on localhost, and hence the path!
$api_acc_type = file_get_contents($ACC_SETING);

if ($api_acc_type ==“Live”){
$set_alpaca_acc_type = False;

}
if($api_acc_type ==“Paper”){
$set_alpaca_acc_type = True;

}

	$key_file = "C:/php/www/Stock_Market/API/alpaca.KEY"; // I was running the code on localhost, and hence the path!
	$key_secret = "C:/php/www/Stock_Market/API/alpaca.SECRET"; // I was running the code on localhost, and hence the path!
$api_key = file_get_contents($key_file);
$api_secret = file_get_contents($key_secret);

										//Paper trading

$alpaca = new Alpaca($api_key, $api_secret, $set_alpaca_acc_type);

Trading_name = _POST[‘Trading_name’];
symbol = _POST[‘symbol’];
dirty_price = _POST[‘price’];
ORDER_TYPE = _POST[‘ORDER_TYPE’];
quantity = _POST[‘quantity’];

$get_action = $_GET['action'];

if ($dirty_price < 1) {
$price = round($dirty_price,4, PHP_ROUND_HALF_UP);

}else {
$price = round($dirty_price,2, PHP_ROUND_HALF_UP);
}
$resp = $alpaca->getAccount();
if ($get_action==‘trade’){

if ( $ORDER_TYPE== "buy") {

//if we are buying a stock

$test = json_encode(($alpaca ->createOrder($symbol,
$quantity,
$ORDER_TYPE,
‘limit’, //limit
‘day’,
$price, //limit_price
null,
null)->getResponse()));

}

//if we are selling a stock, SEND IT AS A MARKET ORDER 

if ($ORDER_TYPE== "sell"){

$test = json_encode(($alpaca ->createOrder($symbol,
$quantity,
$ORDER_TYPE,
‘market’, //limit
‘day’,
null, //limit_price
null,
null)->getResponse()));

}

}if (!isset($test)){
$account = json_encode(($alpaca ->getAccount()->getResponse()));}
//echo $get_action;
if ($test <>""){echo $test;}else{
echo $account;}