Skip to main content

API Authentication

Learn how to securely authenticate with the PMF Finance API to access your account data and execute trades programmatically.

Authentication Methods

API Keys

PMF Finance uses API key authentication for secure access to your account data and trading functionality.

Generating API Keys

  1. Log in to your PMF Finance account
  2. Navigate to Settings > API Keys
  3. Click "Generate New API Key"
  4. Set permissions and restrictions
  5. Securely store your API key and secret

API Key Types

  • Read-Only: Access to account data and market information
  • Trading: Full trading capabilities including order placement
  • Admin: Complete account management (use with extreme caution)

Authentication Headers

Required Headers

X-API-Key: your_api_key_here
X-API-Secret: your_api_secret_here
X-API-Timestamp: 1640995200000
X-API-Signature: calculated_signature

Signature Calculation

const crypto = require('crypto');

function createSignature(secret, timestamp, method, path, body = '') {
const message = timestamp + method.toUpperCase() + path + body;
return crypto.createHmac('sha256', secret).update(message).digest('hex');
}

// Example usage
const timestamp = Date.now().toString();
const method = 'GET';
const path = '/api/v1/account/balance';
const signature = createSignature(apiSecret, timestamp, method, path);

Security Best Practices

API Key Management

  • Secure Storage: Never store API keys in client-side code or public repositories
  • Environment Variables: Use environment variables for API key storage
  • Regular Rotation: Rotate API keys regularly for enhanced security
  • Principle of Least Privilege: Grant only necessary permissions to each API key

Network Security

  • HTTPS Only: All API requests must use HTTPS
  • IP Whitelisting: Restrict API access to specific IP addresses when possible
  • Rate Limiting: Respect rate limits to avoid account suspension
  • Request Signing: Always sign requests with your API secret

Rate Limiting

Rate Limit Structure

  • Public Endpoints: 100 requests per minute
  • Private Endpoints: 60 requests per minute
  • Trading Endpoints: 30 requests per minute
  • Burst Allowance: Short bursts up to 2x the limit

Rate Limit Headers

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1640995260

Handling Rate Limits

async function makeAPIRequest(url, options) {
try {
const response = await fetch(url, options);

if (response.status === 429) {
const resetTime = response.headers.get('X-RateLimit-Reset');
const waitTime = (resetTime * 1000) - Date.now();

console.log(`Rate limited. Waiting ${waitTime}ms`);
await new Promise(resolve => setTimeout(resolve, waitTime));

return makeAPIRequest(url, options); // Retry
}

return response;
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}

Error Handling

Authentication Errors

{
"error": "INVALID_API_KEY",
"message": "The provided API key is invalid or expired",
"code": 401
}

Common Error Codes

  • 401 Unauthorized: Invalid or missing authentication credentials
  • 403 Forbidden: Valid credentials but insufficient permissions
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server-side error

Error Response Format

{
"error": "ERROR_CODE",
"message": "Human-readable error description",
"code": 400,
"details": {
"field": "specific_field_with_error",
"reason": "validation_failed"
}
}

Testing Authentication

Test Endpoint

Use the following endpoint to test your authentication setup:

GET /api/v1/auth/test

Example Request

curl -X GET "https://api.pmf.finance/v1/auth/test" \
-H "X-API-Key: your_api_key" \
-H "X-API-Secret: your_api_secret" \
-H "X-API-Timestamp: 1640995200000" \
-H "X-API-Signature: calculated_signature"

Success Response

{
"success": true,
"message": "Authentication successful",
"user_id": "user_12345",
"permissions": ["read", "trade"],
"rate_limit": {
"limit": 60,
"remaining": 59,
"reset": 1640995260
}
}

SDK and Libraries

Official SDKs

  • JavaScript/Node.js: npm install pmf-finance-sdk
  • Python: pip install pmf-finance
  • Go: go get github.com/pmf-finance/go-sdk

JavaScript SDK Example

const PMFFinance = require('pmf-finance-sdk');

const client = new PMFFinance({
apiKey: process.env.PMF_API_KEY,
apiSecret: process.env.PMF_API_SECRET,
sandbox: false // Set to true for testing
});

// Test authentication
async function testAuth() {
try {
const result = await client.auth.test();
console.log('Authentication successful:', result);
} catch (error) {
console.error('Authentication failed:', error);
}
}

Python SDK Example

import os
from pmf_finance import PMFFinanceClient

client = PMFFinanceClient(
api_key=os.getenv('PMF_API_KEY'),
api_secret=os.getenv('PMF_API_SECRET'),
sandbox=False # Set to True for testing
)

# Test authentication
try:
result = client.auth.test()
print(f"Authentication successful: {result}")
except Exception as error:
print(f"Authentication failed: {error}")

Sandbox Environment

Sandbox Access

  • Base URL: https://sandbox-api.pmf.finance
  • Test Credentials: Use separate API keys for sandbox testing
  • Fake Data: Sandbox uses simulated market data and balances
  • No Real Money: All transactions are simulated

Sandbox Features

  • Full API functionality without real money risk
  • Reset account balances and positions
  • Test trading strategies and integrations
  • Simulate various market conditions

Migration and Versioning

API Versioning

  • Current Version: v1
  • Version Header: X-API-Version: v1
  • Backward Compatibility: Maintained for at least 12 months
  • Deprecation Notice: 90-day notice for breaking changes

Migration Guide

When new API versions are released:

  1. Review changelog and breaking changes
  2. Test integration in sandbox environment
  3. Update authentication if required
  4. Deploy changes during low-traffic periods
  5. Monitor for any issues post-deployment

Next Steps

  • Generate your API keys in the platform settings
  • Test authentication using the test endpoint
  • Explore available API endpoints
  • Review API examples for common use cases
  • Join our developer community for support and updates