A PHP SDK for interacting with the Groww Trading API.
Install via Composer:
composer require gopalindians/groww-php-sdkuse Groww\API\Client;
// Initialize the client with your API key
$groww = new Client('your_api_key_here');
// Optional: Enable logging
$groww->setLogging(true, function($level, $message, $context) {
// Custom logging implementation
error_log("[$level] $message " . json_encode($context));
});try {
$orderData = [
'validity' => 'DAY',
'exchange' => 'NSE',
'transaction_type' => 'BUY',
'order_type' => 'MARKET',
'price' => 0,
'product' => 'CNC',
'quantity' => 1,
'segment' => 'CASH',
'trading_symbol' => 'IDEA'
];
$result = $groww->orders()->create($orderData);
print_r($result);
} catch (Groww\API\Exceptions\GrowwApiException $e) {
echo "Error: " . $e->getMessage() . " (Code: " . $e->getErrorCode() . ")";
}try {
$orderDetails = $groww->orders()->details('GMK39038RDT490CCVRO');
print_r($orderDetails);
} catch (Groww\API\Exceptions\GrowwApiException $e) {
echo "Error: " . $e->getMessage() . " (Code: " . $e->getErrorCode() . ")";
}try {
$result = $groww->orders()->cancel('GMK39038RDT490CCVRO');
print_r($result);
} catch (Groww\API\Exceptions\GrowwApiException $e) {
echo "Error: " . $e->getMessage() . " (Code: " . $e->getErrorCode() . ")";
}try {
$holdings = $groww->portfolio()->holdings();
print_r($holdings);
} catch (Groww\API\Exceptions\GrowwApiException $e) {
echo "Error: " . $e->getMessage() . " (Code: " . $e->getErrorCode() . ")";
}try {
$positions = $groww->portfolio()->positions();
print_r($positions);
} catch (Groww\API\Exceptions\GrowwApiException $e) {
echo "Error: " . $e->getMessage() . " (Code: " . $e->getErrorCode() . ")";
}try {
$searchResults = $groww->instruments()->search('RELIANCE');
print_r($searchResults);
} catch (Groww\API\Exceptions\GrowwApiException $e) {
echo "Error: " . $e->getMessage() . " (Code: " . $e->getErrorCode() . ")";
}try {
$quotes = $groww->liveData()->quotes(['RELIANCE', 'IDEA']);
print_r($quotes);
} catch (Groww\API\Exceptions\GrowwApiException $e) {
echo "Error: " . $e->getMessage() . " (Code: " . $e->getErrorCode() . ")";
}try {
$candleData = $groww->historicalData()->candles(
'RELIANCE',
'1d',
'2023-01-01',
'2023-01-31'
);
print_r($candleData);
} catch (Groww\API\Exceptions\GrowwApiException $e) {
echo "Error: " . $e->getMessage() . " (Code: " . $e->getErrorCode() . ")";
}try {
$availableMargin = $groww->margin()->available();
print_r($availableMargin);
} catch (Groww\API\Exceptions\GrowwApiException $e) {
echo "Error: " . $e->getMessage() . " (Code: " . $e->getErrorCode() . ")";
}The SDK throws GrowwApiException when an error occurs. You can catch this exception to handle errors gracefully:
try {
// API operations
} catch (Groww\API\Exceptions\GrowwRateLimitException $e) {
// Handle rate limiting specifically
echo "Rate limit exceeded. Try again after " . $e->getWaitTime() . " seconds.\n";
sleep($e->getWaitTime());
// Retry the request
} catch (Groww\API\Exceptions\GrowwApiException $e) {
echo "Error message: " . $e->getMessage() . "\n";
echo "Error code: " . $e->getErrorCode() . "\n";
// Handle different error codes
switch ($e->getErrorCode()) {
case 'GA001':
echo "Bad request - check your parameters\n";
break;
case 'GA005':
echo "Authentication error - check your API key\n";
break;
default:
echo "Unknown error occurred\n";
break;
}
}This SDK implements several security best practices:
- Input Validation: All inputs are validated before being sent to the API.
- TLS/SSL Verification: HTTPS connections are enforced by default.
- Rate Limiting Protection: Built-in rate limiting with exponential backoff.
- Parameter Sanitization: All parameters are sanitized to prevent injection attacks.
- Sensitive Data Protection: API keys and other sensitive data are redacted in logs.
- Error Handling: Comprehensive error handling for security-related issues.
The SDK includes a secure logging system that redacts sensitive information:
// Enable logging with a custom logger
$groww->setLogging(true, function($level, $message, $context) {
// Custom logging implementation
// All sensitive data is automatically redacted
});The SDK comes with a comprehensive test suite. To run the tests:
- Install development dependencies:
composer install --dev- Run PHPUnit:
./vendor/bin/phpunitThis project uses GitHub Actions for continuous integration. Every time code is pushed to the main or master branch, or when a pull request is created against these branches, the test suite is automatically executed on multiple PHP versions (7.4, 8.0, and 8.1).
The CI pipeline:
- Sets up the PHP environment
- Installs dependencies via Composer
- Runs the PHPUnit test suite
You can check the workflow configuration in the .github/workflows/php-tests.yml file.
You can use the existing test suite as a reference for writing your own tests. The SDK provides mock responses and helpers to make testing easier:
use Groww\API\Tests\TestCase;
use Groww\API\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Client as HttpClient;
class YourTest extends TestCase
{
public function testYourMethod()
{
// Create a mock response
$mockResponse = $this->createSuccessResponse(['data' => 'value']);
// Set up mock handler
$mock = new MockHandler([
new Response(200, [], json_encode($mockResponse))
]);
$handlerStack = HandlerStack::create($mock);
$httpClient = new HttpClient(['handler' => $handlerStack]);
// Create client with mock
$client = new Client($this->getTestApiKey());
$client->setHttpClient($httpClient);
// Test your code
$result = $client->get('/endpoint');
// Assert results
$this->assertEquals($mockResponse, $result);
}
}For the full API reference, visit the Groww API documentation at: https://groww.in/trade-api/docs/curl
MIT