Skip to content

Repository files navigation

Groww Trading API

A FastAPI application for interacting with the Groww trading platform with enhanced features including portfolio management, stock quotes, and market status.

πŸš€ Features

  • Order Management: Place BUY/SELL orders with automatic market/limit detection
  • Stock Quotes: Get real-time quotes for single or multiple stocks
  • Portfolio Tracking: View current holdings and P&L (placeholder)
  • Market Status: Check if markets are open/closed
  • Health Monitoring: API health checks and status monitoring
  • Push Notifications: Get notified about order status via Pushbullet
  • Auto-retry: Automatic token refresh and retry logic

πŸ› οΈ Local Development

Prerequisites

  1. Python 3.8+ installed
  2. Docker installed (for containerized deployment)
  3. AWS CLI configured with your credentials

Quick Start

  1. Clone and setup:

    git clone <your-repo>
    cd Groww
  2. Create environment file:

    cp .env.example .env
    # Edit .env with your actual credentials
  3. Start development server:

    ./run-local.sh
  4. Access your API:

Development Workflow

Use the interactive development menu:

./dev-workflow.sh

This provides options for:

  • πŸš€ Starting local server
  • πŸ§ͺ Running API tests
  • 🐳 Building Docker images
  • πŸ“¦ Deploying to Lambda
  • πŸ“Š Viewing logs
  • πŸ”„ Updating environment variables

Manual Commands

Start local server:

./run-local.sh

Test API endpoints:

./test-api.sh

Build Docker image:

sudo docker build -t groww-trading-api:dev .

πŸ“‘ API Endpoints

Basic Endpoints

  • GET / - Welcome message
  • GET /hello - Hello message
  • GET /health - Health check
  • GET /market-status - Market open/closed status

Stock Data

  • GET /quote/{ticker} - Get single stock quote
  • POST /quotes - Get multiple stock quotes

Trading

  • POST /order - Place trading order
  • GET /orders_list - Get order history
  • POST /stop-loss/sell - Place stop loss sell order
  • POST /gtt/buy - Place GTT buy order

GTT (Good Till Triggered) Orders

  • POST /gtt/order - Place GTT order (buy/sell)
  • PUT /gtt/order - Modify existing GTT order
  • GET /gtt/orders - Get all GTT orders
  • DELETE /gtt/order/{gtt_id} - Cancel GTT order

Portfolio

  • GET /portfolio - Get portfolio holdings (placeholder)

Utilities

  • POST /test-notification - Test push notifications

Example Usage

Get stock quote:

curl http://localhost:8000/quote/SBIN

Get multiple quotes:

curl -X POST http://localhost:8000/quotes \
  -H "Content-Type: application/json" \
  -d '["SBIN", "RELIANCE", "TCS"]'

Place order:

curl -X POST http://localhost:8000/order \
  -H "Content-Type: application/json" \
  -d '{
    "ticker": "SBIN",
    "quantity": 1,
    "transaction_type": "BUY",
    "price": 800
  }'

Place stop loss sell order:

curl -X POST http://localhost:8000/stop-loss/sell \
  -H "Content-Type: application/json" \
  -d '{
    "ticker": "SBIN",
    "quantity": 10,
    "stop_loss_price": 750,
    "limit_price": 745
  }'

Place GTT buy order:

curl -X POST http://localhost:8000/gtt/buy \
  -H "Content-Type: application/json" \
  -d '{
    "ticker": "RELIANCE",
    "quantity": 5,
    "transaction_type": "BUY",
    "trigger_price": 2800,
    "limit_price": 2805
  }'

Get GTT orders:

curl http://localhost:8000/gtt/orders

πŸš€ Deployment Options

Option 1: AWS Lambda (Container) - Recommended

This deployment method uses Docker containers to deploy to AWS Lambda, which is ideal for applications larger than 50MB.

Prerequisites

  1. Install Docker and ensure it's running
  2. Install the AWS CLI and configure it with your credentials:
    pip install awscli
    aws configure
    

Deployment Steps

  1. Create your .env file with required environment variables:

    API_KEY=your_api_key_here
    TOTP_SECRET=your_totp_secret_here
    PUSH_TOKEN=your_push_token_here
    
  2. Deploy to Lambda:

    ./deploy-lambda.sh
    
  3. Set environment variables:

    ./set-env-vars.sh
    

Monitoring and Management

  • View function logs:

    aws logs tail /aws/lambda/groww-trading-api --follow --region us-east-1
    
  • Update function code (after making changes):

    ./deploy-lambda.sh
    
  • Delete the function:

    aws lambda delete-function --function-name groww-trading-api --region us-east-1
    

Option 2: AWS Elastic Beanstalk (Legacy)

Prerequisites

  1. Install the AWS CLI and configure it with your credentials:

    pip install awscli
    aws configure
    
  2. Install the Elastic Beanstalk CLI:

    pip install awsebcli
    

Deployment Steps

  1. Initialize your Elastic Beanstalk application (first time only):

    eb init -p python-3.8 groww-api --region <your-region>
    
  2. Create an environment (first time only):

    eb create groww-api-env
    
  3. Set up environment variables in the Elastic Beanstalk console:

    • API_KEY
    • TOTP_SECRET
    • PUSH_TOKEN
  4. Deploy your application:

    eb deploy
    

Alternatively, you can use the provided deploy.sh script:

./deploy.sh

Monitoring and Management

  • To view the application status:

    eb status
    
  • To view application logs:

    eb logs
    
  • To open the application in a browser:

    eb open
    
  • To terminate the environment when no longer needed:

    eb terminate groww-api-env
    

πŸ”§ Configuration

Environment Variables

Create a .env file with:

API_KEY=your_groww_api_key
TOTP_SECRET=your_totp_secret_key
PUSH_TOKEN=your_pushbullet_token

Development vs Production

  • Local Development: Uses uvicorn with auto-reload
  • Lambda Deployment: Uses mangum adapter for serverless
  • Environment: Automatically detected based on runtime

πŸ§ͺ Testing

Automated Testing

./test-api.sh

Manual Testing

Visit http://localhost:8000/docs for interactive API documentation.

Load Testing

# Install hey (HTTP load testing tool)
sudo apt install hey

# Test with 100 requests, 10 concurrent
hey -n 100 -c 10 http://localhost:8000/health

πŸ“Š Monitoring

Local Development

  • Server logs appear in terminal
  • Access logs via uvicorn output

Lambda Production

# View real-time logs
aws logs tail /aws/lambda/groww-trading-api --follow --region us-east-1

# View specific time range
aws logs tail /aws/lambda/groww-trading-api --since 1h --region us-east-1

πŸ”’ Security

  • Environment variables stored securely in Lambda
  • API keys never logged or exposed
  • HTTPS enforced in production
  • Input validation on all endpoints

πŸ’° Cost Optimization

Lambda Benefits

  • Pay only for actual usage
  • Automatic scaling
  • No idle costs
  • ~85-95% cost savings vs traditional servers

Estimated Costs

  • 1,000 requests/month: ~$0.04
  • 10,000 requests/month: ~$0.40
  • 100,000 requests/month: ~$4.00

🚨 Troubleshooting

Common Issues

Token Authentication Errors:

  • Check your API_KEY and TOTP_SECRET
  • Ensure TOTP is generating correctly
  • Token auto-refreshes on failure

Local Server Won't Start:

# Check if port 8000 is in use
lsof -i :8000

# Kill existing processes
pkill -f uvicorn

Docker Build Issues:

# Clean Docker cache
sudo docker system prune -f

# Rebuild without cache
sudo docker build --no-cache -t groww-trading-api:dev .

Lambda Deployment Issues:

# Check AWS credentials
aws sts get-caller-identity

# Verify ECR permissions
aws ecr describe-repositories --region us-east-1

πŸ“ Development Notes

Adding New Features

  1. Add endpoint to app.py
  2. Test locally with ./run-local.sh
  3. Test with ./test-api.sh
  4. Deploy with ./deploy-lambda.sh

Code Structure

β”œβ”€β”€ app.py              # Main FastAPI application
β”œβ”€β”€ lambda_handler.py   # Lambda adapter
β”œβ”€β”€ requirements.txt    # Python dependencies
β”œβ”€β”€ Dockerfile         # Container definition
β”œβ”€β”€ .env               # Environment variables (local)
β”œβ”€β”€ run-local.sh       # Local development server
β”œβ”€β”€ test-api.sh        # API testing script
β”œβ”€β”€ dev-workflow.sh    # Development workflow menu
β”œβ”€β”€ deploy-lambda.sh   # Lambda deployment
└── set-env-vars.sh    # Environment variable setup

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Test locally with ./dev-workflow.sh
  4. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages