Add StochasticCross indicator support in CustomScenario and TradeChart components

- Implemented StochasticCross indicator in CustomScenario with associated parameters and labels.
- Enhanced TradeChart to visualize StochasticCross data, including %K and %D series.
- Updated API and types to include kFactor and dFactor properties for StochasticCross.
- Modified backtest and scenario pages to incorporate StochasticCross in indicator lists and parameter mappings.
This commit is contained in:
2025-11-24 11:04:05 +07:00
parent 43d7c5c929
commit 18f868a221
9 changed files with 685 additions and 15 deletions

View File

@@ -0,0 +1,358 @@
# .NET 10 Upgrade Documentation Plan
## Overview
This document outlines the comprehensive plan for upgrading the Managing Apps solution from .NET 8 to .NET 10. The upgrade involves multiple .NET projects, Orleans clustering, and requires careful planning to minimize risks and ensure performance improvements.
## Current State Assessment
### Project Structure
- **Backend**: Multiple .NET projects targeting `net8.0`
- Managing.Api (ASP.NET Core Web API)
- Managing.Application (Business logic)
- Managing.Domain (Domain models)
- Managing.Infrastructure.* (Database, Exchanges, Storage, etc.)
- Orleans 9.2.1 clustering with PostgreSQL persistence
- **Frontend**: React/TypeScript application (not affected by .NET upgrade)
### Key Dependencies
- Orleans 9.2.1 → Potential upgrade to Orleans 10.x
- Entity Framework Core 8.0.11 → 10.x
- ASP.NET Core 8.0.x → 10.x
- PostgreSQL/Npgsql 8.0.10 → Latest compatible version
- InfluxDB client and other infrastructure dependencies
## Upgrade Strategy
### Phase 1: Preparation (Week 1-2)
#### 1.1 Development Environment Setup
- [ ] Install .NET 10 SDK on all development machines
- [ ] Update CI/CD pipelines to support .NET 10
- [ ] Create dedicated upgrade branch (`feature/net10-upgrade`)
- [ ] Set up parallel environments (keep .NET 8 for rollback)
#### 1.2 Dependency Analysis
- [ ] Audit all NuGet packages for .NET 10 compatibility
- [ ] Identify packages requiring updates
- [ ] Test critical third-party packages in isolation
- [ ] Document breaking changes in dependencies
#### 1.3 Documentation Updates
- [ ] Update Dockerfiles (`FROM mcr.microsoft.com/dotnet/sdk:8.0``10.0`)
- [ ] Update deployment scripts
- [ ] Update README and architecture docs
- [ ] Create rollback procedures
### Phase 2: Core Framework Upgrade (Week 3-4)
#### 2.1 Project File Updates
**Priority Order:**
1. Managing.Common, Managing.Core (lowest risk)
2. Managing.Domain (pure domain logic)
3. Managing.Infrastructure.* (infrastructure concerns)
4. Managing.Application (business logic)
5. Managing.Api (entry point, highest risk)
**For each project:**
```xml
<!-- Before -->
<TargetFramework>net8.0</TargetFramework>
<!-- After -->
<TargetFramework>net10.0</TargetFramework>
<LangVersion>latest</LangVersion>
```
#### 2.2 Package Updates
**Microsoft Packages (Safe to update first):**
- Microsoft.AspNetCore.* → 10.x
- Microsoft.EntityFrameworkCore → 10.x
- Microsoft.Extensions.* → 10.x
**Third-party Packages:**
- Orleans → 10.x (if available) or stay on 9.x with compatibility testing
- Npgsql → Latest .NET 10 compatible
- All other packages → Update to latest versions
### Phase 3: Orleans Clustering Upgrade (Week 5-6)
#### 3.1 Orleans Assessment
- [ ] Evaluate Orleans 10.x preview vs staying on 9.x
- [ ] Test clustering configuration changes
- [ ] Validate grain persistence compatibility
- [ ] Performance test grain activation/deactivation
#### 3.2 Configuration Updates
```csharp
// Potential Orleans 10.x configuration changes
builder.Host.UseOrleans(siloBuilder =>
{
// Updated clustering configuration syntax
siloBuilder.ConfigureServices(services =>
{
// Add any new required services for Orleans 10.x
});
});
```
#### 3.3 Clustering Validation
- [ ] Multi-server clustering test
- [ ] Grain state persistence test
- [ ] Reminders and timers validation
- [ ] Network partitioning simulation
### Phase 4: Database & Infrastructure (Week 7-8)
#### 4.1 Entity Framework Core
- [ ] Run EF Core migration scripts
- [ ] Test query performance with .NET 10
- [ ] Validate async operation improvements
- [ ] Memory usage optimization
#### 4.2 Database Providers
- [ ] PostgreSQL/Npgsql compatibility testing
- [ ] InfluxDB client validation
- [ ] Connection pooling optimization
- [ ] Transaction handling validation
### Phase 5: Performance Optimization (Week 9-10)
#### 5.1 Garbage Collection Tuning
```json
{
"runtimeOptions": {
"configProperties": {
"System.GC.Concurrent": true,
"System.GC.Server": true,
"System.GC.HeapCount": 8,
"System.GC.RetainVM": false,
"System.GC.NoAffinitize": true
}
}
}
```
#### 5.2 Memory Management
- [ ] Implement `Span<T>` where appropriate
- [ ] Optimize string operations
- [ ] Use `ValueTask` for async operations
- [ ] Implement object pooling for hot paths
#### 5.3 Async/Await Optimization
- [ ] Use `ConfigureAwait(false)` appropriately
- [ ] Implement `IAsyncEnumerable` for streaming
- [ ] Optimize async state machines
## Risk Assessment
### High Risk Areas
1. **Orleans Clustering**: Most complex, potential for downtime
2. **Database Operations**: EF Core changes could affect queries
3. **Third-party Dependencies**: May not support .NET 10 immediately
### Medium Risk Areas
1. **ASP.NET Core Middleware**: Authentication, routing changes
2. **Serialization**: JSON/binary serialization changes
3. **Logging and Monitoring**: Integration compatibility
### Low Risk Areas
1. **Domain Models**: Pure C# logic, minimal changes
2. **Business Logic**: Framework-agnostic code
## Testing Strategy
### Unit Testing
- [ ] All existing tests pass on .NET 10
- [ ] New tests for .NET 10 specific features
- [ ] Performance regression tests
### Integration Testing
- [ ] API endpoint testing
- [ ] Database integration tests
- [ ] Orleans grain communication tests
- [ ] External service integration
### Performance Testing
- [ ] Memory usage benchmarks
- [ ] Request throughput testing
- [ ] Orleans grain activation latency
- [ ] Database query performance
### Staging Environment
- [ ] Full system testing in staging
- [ ] Load testing with production-like data
- [ ] Multi-day stability testing
- [ ] Failover and recovery testing
## Rollback Plan
### Immediate Rollback (First 24 hours)
- [ ] Keep .NET 8 containers available
- [ ] Feature flags for problematic features
- [ ] Database backup and restore procedures
### Gradual Rollback (1-7 days)
- [ ] Roll back individual services if needed
- [ ] Maintain API compatibility during rollback
- [ ] Client-side feature toggles
### Emergency Procedures
- [ ] Complete environment rollback to .NET 8
- [ ] Database state recovery
- [ ] User communication plan
## Success Metrics
### Performance Improvements
- [ ] 10-20% reduction in memory usage
- [ ] 5-15% improvement in request throughput
- [ ] Reduced GC pause times
- [ ] Faster application startup
### Reliability Improvements
- [ ] Zero downtime during upgrade
- [ ] No data loss or corruption
- [ ] All existing functionality preserved
- [ ] Improved error handling and logging
### Development Experience
- [ ] Faster build times
- [ ] Better debugging experience
- [ ] Access to latest .NET features
- [ ] Improved developer productivity
## Timeline and Milestones
### Week 1-2: Preparation
- [ ] Environment setup complete
- [ ] Dependency analysis finished
- [ ] Documentation updated
### Week 3-4: Core Upgrade
- [ ] All project files updated to .NET 10
- [ ] Microsoft packages updated
- [ ] Basic functionality testing passed
### Week 5-6: Orleans Upgrade
- [ ] Orleans configuration updated
- [ ] Clustering validation complete
- [ ] Grain functionality verified
### Week 7-8: Infrastructure
- [ ] Database operations validated
- [ ] External integrations tested
- [ ] Performance benchmarks established
### Week 9-10: Optimization
- [ ] Memory optimizations implemented
- [ ] Performance tuning complete
- [ ] Final testing and validation
### Week 11-12: Production Deployment
- [ ] Staging environment validation
- [ ] Production deployment
- [ ] Post-deployment monitoring
- [ ] Go-live decision
## Communication Plan
### Internal Stakeholders
- [ ] Weekly progress updates
- [ ] Risk assessments and mitigation plans
- [ ] Go/no-go decision checkpoints
### External Users
- [ ] Pre-upgrade notification
- [ ] Maintenance window communication
- [ ] Post-upgrade feature announcements
## Monitoring and Observability
### Key Metrics to Monitor
- Application memory usage
- CPU utilization
- Request latency and throughput
- Error rates and exceptions
- Orleans cluster health
- Database connection pools
- Garbage collection statistics
### Alerting Setup
- [ ] Memory usage thresholds
- [ ] Error rate monitoring
- [ ] Performance degradation alerts
- [ ] Orleans cluster health checks
## Contingency Plans
### Package Compatibility Issues
- [ ] Pin incompatible packages to working versions
- [ ] Implement adapter patterns for breaking changes
- [ ] Vendor critical dependencies if needed
### Performance Regression
- [ ] Performance profiling and optimization
- [ ] Feature flags for performance-intensive features
- [ ] Gradual rollout with A/B testing
### Orleans Issues
- [ ] Alternative clustering configurations
- [ ] Grain state migration procedures
- [ ] Fallback to single-server mode
## Resources Required
### Team
- 2-3 Senior .NET Developers
- 1 DevOps Engineer
- 1 QA Engineer
- 1 Product Owner
### Infrastructure
- Staging environment identical to production
- Performance testing environment
- Backup and recovery systems
- Monitoring and alerting setup
### Budget
- Development time: 8-12 weeks
- Infrastructure costs for testing environments
- Third-party tool licenses if needed
- Training and documentation time
---
## Appendices
### Appendix A: Package Compatibility Matrix
| Package | Current Version | .NET 10 Compatible | Notes |
|---------|-----------------|-------------------|-------|
| Microsoft.AspNetCore.* | 8.0.x | 10.x | Direct upgrade |
| Microsoft.EntityFrameworkCore | 8.0.11 | 10.x | Migration scripts required |
| Microsoft.Orleans.* | 9.2.1 | 10.x (preview) | Major version upgrade |
### Appendix B: Breaking Changes Checklist
- [ ] ASP.NET Core authentication middleware
- [ ] EF Core query behavior changes
- [ ] Orleans grain activation patterns
- [ ] Serialization format changes
- [ ] Logging framework updates
### Appendix C: Performance Benchmarks
**Baseline (.NET 8):**
- Memory usage: [TBD]
- Request throughput: [TBD]
- GC pause time: [TBD]
**Target (.NET 10):**
- Memory usage: [TBD] (10-20% reduction)
- Request throughput: [TBD] (5-15% improvement)
- GC pause time: [TBD] (significant reduction)
---
**Document Version:** 1.0
**Last Updated:** November 24, 2025
**Authors:** Development Team
**Reviewers:** Architecture Team, DevOps Team

View File

@@ -0,0 +1,162 @@
# .NET 10 Upgrade Initiative
## Quick Reference Guide
This document provides a quick overview of our .NET 10 upgrade plan. For detailed information, see [NET10-Upgrade-Plan.md](NET10-Upgrade-Plan.md).
## Current Status
- **Current Framework**: .NET 8.0
- **Target Framework**: .NET 10.0
- **Status**: Planning Phase
- **Estimated Timeline**: 10-12 weeks
## Key Objectives
### Performance Improvements
- **Memory Usage**: 10-20% reduction through improved GC
- **Throughput**: 5-15% improvement in request handling
- **Startup Time**: Faster application initialization
- **Resource Efficiency**: Better CPU and memory utilization
### Modernization Benefits
- Access to latest .NET features and optimizations
- Improved async/await performance
- Better debugging and development experience
- Enhanced security features
## Risk Assessment
### High Risk Areas 🚨
- **Orleans Clustering**: Complex distributed system upgrade
- **Database Operations**: EF Core query behavior changes
- **Third-party Dependencies**: May require updates or workarounds
### Medium Risk Areas ⚠️
- **ASP.NET Core**: Middleware and authentication changes
- **Serialization**: JSON/binary format updates
- **External Integrations**: API compatibility
### Low Risk Areas ✅
- **Domain Logic**: Framework-independent business rules
- **Pure C# Code**: Minimal framework dependencies
## Upgrade Phases
### Phase 1: Preparation (Weeks 1-2)
- [ ] Environment setup and dependency analysis
- [ ] Create upgrade branch and rollback procedures
- [ ] Update CI/CD pipelines
### Phase 2: Core Framework (Weeks 3-4)
- [ ] Update all project files to `net10.0`
- [ ] Upgrade Microsoft packages (EF Core, ASP.NET Core)
- [ ] Basic functionality validation
### Phase 3: Orleans Clustering (Weeks 5-6)
- [ ] Evaluate Orleans 10.x compatibility
- [ ] Update clustering configuration
- [ ] Validate grain persistence and communication
### Phase 4: Infrastructure (Weeks 7-8)
- [ ] Database provider updates (Npgsql, InfluxDB)
- [ ] External service integrations
- [ ] Performance benchmarking
### Phase 5: Optimization (Weeks 9-10)
- [ ] Memory management improvements
- [ ] Async/await optimizations
- [ ] Final performance tuning
### Phase 6: Production (Weeks 11-12)
- [ ] Staging environment validation
- [ ] Production deployment
- [ ] Post-deployment monitoring
## Quick Wins (Immediate Benefits)
### Code Optimizations
```csharp
// Before (.NET 8)
string result = data.ToString();
// After (.NET 10) - Better memory efficiency
ReadOnlySpan<char> span = data.AsSpan();
```
### Configuration Improvements
```json
{
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true,
"System.GC.HeapCount": 8,
"System.GC.RetainVM": false
}
}
}
```
## Success Metrics
| Metric | Baseline (.NET 8) | Target (.NET 10) | Improvement |
|--------|------------------|------------------|-------------|
| Memory Usage | TBD | TBD | -10-20% |
| Request Throughput | TBD | TBD | +5-15% |
| GC Pause Time | TBD | TBD | Significant reduction |
| Startup Time | TBD | TBD | Faster |
## Key Contacts
- **Technical Lead**: [Name]
- **DevOps Lead**: [Name]
- **QA Lead**: [Name]
- **Product Owner**: [Name]
## Emergency Contacts
- **Rollback Procedures**: See [NET10-Upgrade-Plan.md](NET10-Upgrade-Plan.md#rollback-plan)
- **Incident Response**: Contact DevOps on-call
- **Business Continuity**: Product Owner + DevOps Lead
## Related Documentation
- **[Detailed Upgrade Plan](NET10-Upgrade-Plan.md)**: Complete technical specification
- **[Architecture Overview](../docs/Architecture.drawio)**: System architecture diagrams
- **[Worker Processing](./Workers%20processing/)**: Background processing documentation
- **[Deployment Guide](./Workers%20processing/05-Deployment-Architecture.md)**: Infrastructure setup
## Weekly Checkpoints
### Week 1: Kickoff
- [ ] Team alignment on objectives
- [ ] Environment setup verification
- [ ] Baseline performance metrics captured
### Week 6: Mid-point Review
- [ ] Core framework upgrade completed
- [ ] Orleans clustering validated
- [ ] Go/no-go decision for Phase 2
### Week 10: Pre-production
- [ ] All optimizations implemented
- [ ] Staging environment fully tested
- [ ] Performance targets validated
### Week 12: Production Go-live
- [ ] Successful production deployment
- [ ] Performance monitoring active
- [ ] Rollback procedures documented
---
## Need Help?
- **Questions**: Create issue in project repository with `upgrade-plan` label
- **Blockers**: Tag technical lead and DevOps lead
- **Schedule Changes**: Notify product owner and team lead
---
**Document Version:** 1.0
**Last Updated:** November 24, 2025
**Next Review:** Weekly during upgrade

View File

@@ -54,6 +54,10 @@ const CustomScenario: React.FC<ICustomScenario> = ({
params = ['period', 'stochPeriods', 'signalPeriods', 'smoothPeriods'];
break;
case IndicatorType.StochasticCross:
params = ['stochPeriods', 'signalPeriods', 'smoothPeriods', 'kFactor', 'dFactor'];
break;
case IndicatorType.Stc:
case IndicatorType.LaggingStc:
params = ['cyclePeriods', 'fastPeriods', 'slowPeriods'];
@@ -97,6 +101,9 @@ const CustomScenario: React.FC<ICustomScenario> = ({
case IndicatorType.StochRsiTrend:
label = 'Stoch RSI Trend';
break;
case IndicatorType.StochasticCross:
label = 'Stochastic Cross';
break;
case IndicatorType.Stc:
label = 'STC';
break;

View File

@@ -18,7 +18,6 @@ import type {
Candle,
IndicatorsResultBase,
IndicatorType,
KeyValuePairOfDateTimeAndDecimal,
LightSignal,
Position,
} from '../../../../generated/ManagingApi'
@@ -44,8 +43,8 @@ type ITradeChartProps = {
candles: Candle[]
positions: Position[]
signals: LightSignal[]
walletBalances?: KeyValuePairOfDateTimeAndDecimal[] | null
indicatorsValues?: { [key in keyof typeof IndicatorType]?: IndicatorsResultBase; } | null;
walletBalances?: { key: Date; value: number }[] | null
indicatorsValues?: { [key in keyof typeof IndicatorType]?: IndicatorsResultBase } | null
stream?: Candle | null
width?: number
height?: number
@@ -688,6 +687,55 @@ const TradeChart = ({
paneCount++
}
if (indicatorsValues?.StochasticCross != null) {
const stochKSeries = chart.current.addLineSeries({
color: theme.primary,
lineWidth: 1,
priceLineVisible: false,
priceLineWidth: 1,
title: '%K',
pane: paneCount,
priceFormat: {
precision: 2,
type: 'price',
},
})
const stochK = indicatorsValues.StochasticCross.stoch?.map((w) => {
return {
time: moment(w.date).unix(),
value: w.k,
}
})
// @ts-ignore
stochKSeries.setData(stochK)
const stochDSeries = chart.current.addLineSeries({
color: theme.info,
lineWidth: 1,
priceLineVisible: false,
priceLineWidth: 1,
lineStyle: LineStyle.Dotted,
title: '%D',
pane: paneCount,
priceFormat: {
precision: 2,
type: 'price',
},
})
const stochD = indicatorsValues.StochasticCross.stoch?.map((w) => {
return {
time: moment(w.date).unix(),
value: w.d,
}
})
// @ts-ignore
stochDSeries.setData(stochD)
paneCount++
}
if (indicatorsValues?.StDev != null) {
const stDevSeries = chart.current.addLineSeries({
color: theme.primary,

View File

@@ -4963,6 +4963,8 @@ export interface LightIndicator {
smoothPeriods?: number | null;
stochPeriods?: number | null;
cyclePeriods?: number | null;
kFactor?: number | null;
dFactor?: number | null;
}
export enum IndicatorType {
@@ -4976,6 +4978,7 @@ export enum IndicatorType {
EmaTrend = "EmaTrend",
Composite = "Composite",
StochRsiTrend = "StochRsiTrend",
StochasticCross = "StochasticCross",
Stc = "Stc",
StDev = "StDev",
LaggingStc = "LaggingStc",
@@ -5569,6 +5572,8 @@ export interface IndicatorBase {
smoothPeriods?: number | null;
stochPeriods?: number | null;
cyclePeriods?: number | null;
kFactor?: number | null;
dFactor?: number | null;
user?: User | null;
}

View File

@@ -429,6 +429,8 @@ export interface LightIndicator {
smoothPeriods?: number | null;
stochPeriods?: number | null;
cyclePeriods?: number | null;
kFactor?: number | null;
dFactor?: number | null;
}
export enum IndicatorType {
@@ -442,6 +444,7 @@ export enum IndicatorType {
EmaTrend = "EmaTrend",
Composite = "Composite",
StochRsiTrend = "StochRsiTrend",
StochasticCross = "StochasticCross",
Stc = "Stc",
StDev = "StDev",
LaggingStc = "LaggingStc",
@@ -1035,6 +1038,8 @@ export interface IndicatorBase {
smoothPeriods?: number | null;
stochPeriods?: number | null;
cyclePeriods?: number | null;
kFactor?: number | null;
dFactor?: number | null;
user?: User | null;
}

View File

@@ -103,6 +103,7 @@ const ALL_INDICATORS = [
IndicatorType.LaggingStc,
IndicatorType.SuperTrendCrossEma,
IndicatorType.DualEmaCross,
IndicatorType.StochasticCross,
]
// Indicator type to parameter mapping
@@ -119,6 +120,7 @@ const INDICATOR_PARAM_MAPPING = {
[IndicatorType.SuperTrendCrossEma]: ['period', 'multiplier'],
[IndicatorType.ChandelierExit]: ['period', 'multiplier'],
[IndicatorType.StochRsiTrend]: ['period', 'stochPeriods', 'signalPeriods', 'smoothPeriods'],
[IndicatorType.StochasticCross]: ['stochPeriods', 'signalPeriods', 'smoothPeriods', 'kFactor', 'dFactor'],
[IndicatorType.Stc]: ['cyclePeriods', 'fastPeriods', 'slowPeriods'],
[IndicatorType.LaggingStc]: ['cyclePeriods', 'fastPeriods', 'slowPeriods'],
}

View File

@@ -42,6 +42,7 @@ const ALL_INDICATORS = [
IndicatorType.LaggingStc,
IndicatorType.SuperTrendCrossEma,
IndicatorType.DualEmaCross,
IndicatorType.StochasticCross,
]
// Form Interface

View File

@@ -414,6 +414,88 @@ const IndicatorList: React.FC = () => {
</div>
</>
) : null}
{indicatorType == IndicatorType.StochasticCross ? (
<>
<div className="form-control">
<div className="input-group">
<label htmlFor="stochPeriods" className="label mr-6">
Stoch Periods
</label>
<label className="input-group">
<input
type="number"
placeholder="14"
className="input"
{...register('stochPeriods')}
/>
</label>
</div>
</div>
<div className="form-control">
<div className="input-group">
<label htmlFor="signalPeriods" className="label mr-6">
Signal Periods
</label>
<label className="input-group">
<input
type="number"
placeholder="3"
className="input"
{...register('signalPeriods')}
/>
</label>
</div>
</div>
<div className="form-control">
<div className="input-group">
<label htmlFor="smoothPeriods" className="label mr-6">
Smooth Periods
</label>
<label className="input-group">
<input
type="number"
placeholder="3"
className="input"
{...register('smoothPeriods')}
/>
</label>
</div>
</div>
<div className="form-control">
<div className="input-group">
<label htmlFor="kFactor" className="label mr-6">
K Factor
</label>
<label className="input-group">
<input
type="number"
step="0.1"
placeholder="3.0"
className="input"
{...register('kFactor')}
/>
</label>
</div>
</div>
<div className="form-control">
<div className="input-group">
<label htmlFor="dFactor" className="label mr-6">
D Factor
</label>
<label className="input-group">
<input
type="number"
step="0.1"
placeholder="2.0"
className="input"
{...register('dFactor')}
/>
</label>
</div>
</div>
</>
) : null}
<div className="modal-action">
<button type="submit" className="btn">
Build