Skip to content

Commit

Permalink
Merge pull request #90 from marketcalls/shoonya
Browse files Browse the repository at this point in the history
Major Upgrade - API Analyzer, New Broker Addition Shoonya and Secruity Enhancements
  • Loading branch information
marketcalls authored Dec 6, 2024
2 parents b018ac4 + 201b037 commit 4ede8f1
Show file tree
Hide file tree
Showing 53 changed files with 5,734 additions and 669 deletions.
22 changes: 17 additions & 5 deletions .sample.env
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,22 @@ BROKER_API_SECRET = 'YOUR_BROKER_API_SECRET'

REDIRECT_URL = 'http://127.0.0.1:5000/<broker>/callback' # Change if different

# OpenAlgo Application Key - Change the Key to Some Random Values
APP_KEY = 'dfsd98sdf98dsfjk34ghuu85df'
# Valid Brokers Configuration
VALID_BROKERS = 'fivepaisa,aliceblue,angel,dhan,fyers,icici,kotak,shoonya,upstox,zebu,zerodha'

# Security Configuration
# IMPORTANT: Generate new random values for both keys during setup!

# OpenAlgo Application Key
APP_KEY = '3daa0403ce2501ee7432b75bf100048e3cf510d63d2754f952e93d88bf07ea84'

# Security Pepper - Used for hashing/encryption of sensitive data
# This is used for:
# 1. API key hashing
# 2. User password hashing
# 3. Broker auth token encryption
# Generate a new random string during setup using: python -c "import secrets; print(secrets.token_hex(32))"
API_KEY_PEPPER = 'a25d94718479b170c16278e321ea6c989358bf499a658fd20c90033cef8ce772'

# OpenAlgo Database Configuration
DATABASE_URL = 'sqlite:///db/openalgo.db'
Expand All @@ -26,9 +39,6 @@ FLASK_PORT='5000'
FLASK_DEBUG='False'
FLASK_ENV='development'

# OpenAlgo Flask App Version Management
FLASK_APP_VERSION='1.0.0.13'

# OpenAlgo Rate Limit Settings
LOGIN_RATE_LIMIT_MIN = "5 per minute"
LOGIN_RATE_LIMIT_HOUR = "25 per hour"
Expand All @@ -43,3 +53,5 @@ SMART_ORDER_DELAY = '0.5'
# Session Expiry Time (24-hour format, IST)
# All user sessions will automatically expire at this time daily
SESSION_EXPIRY_TIME = '03:00'

# Note: OpenAlgo version is now managed in utils/version.py
163 changes: 163 additions & 0 deletions Analyzer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# OpenAlgo API Analyzer

The API Analyzer is a powerful feature in OpenAlgo that helps both traders and developers test, validate, and monitor their trading integrations in real-time.

## For Traders

### Key Features

1. **Real-Time Order Validation**
- Test orders without actual execution
- Instant feedback on order parameters
- Validate trading strategies before live deployment

2. **Order Monitoring**
- Real-time view of all order requests
- Track order modifications and cancellations
- Monitor position closures

3. **Strategy Management**
- Track orders by strategy name
- Monitor multiple strategies simultaneously
- Analyze strategy performance

4. **Risk Management**
- Validate order parameters before execution
- Check position sizes and quantities
- Verify price limits and triggers

5. **Notifications**
- Instant visual feedback for all actions
- Sound alerts for important events
- Clear success/error messages

### Benefits

1. **Risk Reduction**
- Test strategies without financial risk
- Validate orders before execution
- Catch potential errors early

2. **Strategy Optimization**
- Fine-tune trading parameters
- Test different order types
- Optimize position sizes

3. **Operational Efficiency**
- Quick validation of trading ideas
- Easy monitoring of multiple strategies
- Instant feedback on order status

4. **Cost Savings**
- Avoid costly trading errors
- Test without brokerage charges
- Optimize trading costs

## For Developers

### Technical Features

1. **API Testing Environment**
- Test all API endpoints without live execution
- Validate request/response formats
- Debug integration issues

2. **Request Validation**
- Automatic parameter validation
- Symbol existence checks
- Price and quantity validations

3. **Response Analysis**
- Detailed response inspection
- Error message analysis
- Status code verification

4. **Real-Time Monitoring**
- WebSocket event monitoring
- Request/response logging
- Performance tracking

5. **Debug Tools**
- View complete request details
- Inspect response data
- Track API call sequence

### Implementation Details

1. **API Endpoints**
- Place Order
- Place Smart Order
- Modify Order
- Cancel Order
- Cancel All Orders
- Close Position

2. **Validation Rules**
- Required field checks
- Data type validation
- Value range verification
- Symbol existence validation
- Exchange compatibility checks

3. **Event System**
- Real-time WebSocket events
- Order status updates
- Error notifications
- System alerts

4. **Data Storage**
- Request logging
- Response tracking
- Error logging
- Performance metrics

### Integration Benefits

1. **Faster Development**
- Quick API testing
- Instant feedback
- Easy debugging

2. **Code Quality**
- Validate integration logic
- Catch errors early
- Ensure proper error handling

3. **Documentation**
- Example requests/responses
- Error scenarios
- Integration patterns

4. **Maintenance**
- Track API usage
- Monitor performance
- Debug issues

## Best Practices

1. **Testing**
- Always test new strategies in analyzer mode first
- Validate all parameters before live trading
- Test edge cases and error scenarios

2. **Monitoring**
- Regularly check analyzer logs
- Monitor error rates
- Track strategy performance

3. **Integration**
- Use proper error handling
- Implement retry logic
- Follow rate limits

4. **Maintenance**
- Keep API keys secure
- Update integration regularly
- Monitor system health

## Support

For technical support or feature requests:
- GitHub Issues
- Community Support
- Documentation Updates
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ OpenAlgo is an open-source, Flask-based Python application designed to bridge th
- **Fyers**
- **ICICI Direct**
- **Kotak**
- **Shoonya**
- **Upstox**
- **Zebu**
- **Zerodha**
Expand All @@ -34,6 +35,13 @@ OpenAlgo is an open-source, Flask-based Python application designed to bridge th
- Dynamic log updates for trade activities
- Contextual notifications with sound alerts

- **API Analyzer**:
- Real-time request validation and testing
- Strategy testing without live execution
- Detailed request/response analysis
- Comprehensive error detection
- See [Analyzer.md](Analyzer.md) for detailed documentation

- **Comprehensive Integration**: Seamlessly connect with Amibroker, Tradingview, Excel, and Google Spreadsheets for smooth data and strategy transition.

- **User-Friendly Interface**: A straightforward Flask-based application interface accessible to traders of all levels of expertise.
Expand Down
21 changes: 12 additions & 9 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from extensions import socketio # Import SocketIO
from limiter import limiter # Import the Limiter instance
from cors import cors # Import the CORS instance
from utils.version import get_version # Import version management

from blueprints.auth import auth_bp
from blueprints.dashboard import dashboard_bp
Expand All @@ -16,14 +17,18 @@
from blueprints.log import log_bp
from blueprints.tv_json import tv_json_bp
from blueprints.brlogin import brlogin_bp
from blueprints.core import core_bp
from blueprints.core import core_bp
from blueprints.analyzer import analyzer_bp # Import the analyzer blueprint
from blueprints.settings import settings_bp # Import the settings blueprint

from restx_api import api_v1_bp

from database.auth_db import init_db as ensure_auth_tables_exists
from database.user_db import init_db as ensure_user_tables_exists
from database.symbol import init_db as ensure_master_contract_tables_exists
from database.apilog_db import init_db as ensure_api_log_tables_exists
from database.analyzer_db import init_db as ensure_analyzer_tables_exists
from database.settings_db import init_db as ensure_settings_tables_exists

from utils.plugin_loader import load_broker_auth_functions

Expand All @@ -46,15 +51,10 @@ def create_app():

load_dotenv()



# Environment variables
app.secret_key = os.getenv('APP_KEY')
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL') # Adjust the environment variable name as necessary

# Initialize SQLAlchemy
# db.init_app(app)

# Register the blueprints
app.register_blueprint(auth_bp)
app.register_blueprint(dashboard_bp)
Expand All @@ -64,7 +64,9 @@ def create_app():
app.register_blueprint(log_bp)
app.register_blueprint(tv_json_bp)
app.register_blueprint(brlogin_bp)
app.register_blueprint(core_bp)
app.register_blueprint(core_bp)
app.register_blueprint(analyzer_bp) # Register the analyzer blueprint
app.register_blueprint(settings_bp) # Register the settings blueprint

# Register RESTx API blueprint
app.register_blueprint(api_v1_bp)
Expand All @@ -75,21 +77,22 @@ def not_found_error(error):

@app.context_processor
def inject_version():
return dict(version=os.getenv('FLASK_APP_VERSION'))
return dict(version=get_version())

return app


def setup_environment(app):
with app.app_context():

#load broker plugins
app.broker_auth_functions = load_broker_auth_functions()
# Ensure all the tables exist
ensure_auth_tables_exists()
ensure_user_tables_exists()
ensure_master_contract_tables_exists()
ensure_api_log_tables_exists()
ensure_analyzer_tables_exists()
ensure_settings_tables_exists()

# Conditionally setup ngrok in development environment
if os.getenv('NGROK_ALLOW') == 'TRUE':
Expand Down
Loading

0 comments on commit 4ede8f1

Please sign in to comment.