backtest-kit 1.5.16 → 1.5.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.cjs +767 -94
- package/build/index.mjs +765 -95
- package/package.json +1 -1
- package/types.d.ts +523 -3
package/package.json
CHANGED
package/types.d.ts
CHANGED
|
@@ -624,11 +624,23 @@ interface IRiskSchema {
|
|
|
624
624
|
}
|
|
625
625
|
/**
|
|
626
626
|
* Risk parameters passed to ClientRisk constructor.
|
|
627
|
-
* Combines schema with runtime dependencies.
|
|
627
|
+
* Combines schema with runtime dependencies and emission callbacks.
|
|
628
628
|
*/
|
|
629
629
|
interface IRiskParams extends IRiskSchema {
|
|
630
630
|
/** Logger service for debug output */
|
|
631
631
|
logger: ILogger;
|
|
632
|
+
/**
|
|
633
|
+
* Callback invoked when a signal is rejected due to risk limits.
|
|
634
|
+
* Called before emitting to riskSubject.
|
|
635
|
+
* Used for event emission to riskSubject (separate from schema callbacks).
|
|
636
|
+
*
|
|
637
|
+
* @param symbol - Trading pair symbol
|
|
638
|
+
* @param params - Risk check arguments
|
|
639
|
+
* @param activePositionCount - Number of active positions at rejection time
|
|
640
|
+
* @param comment - Rejection reason from validation note or "N/A"
|
|
641
|
+
* @param timestamp - Event timestamp in milliseconds
|
|
642
|
+
*/
|
|
643
|
+
onRejected: (symbol: string, params: IRiskCheckArgs, activePositionCount: number, comment: string, timestamp: number) => void | Promise<void>;
|
|
632
644
|
}
|
|
633
645
|
/**
|
|
634
646
|
* Risk interface implemented by ClientRisk.
|
|
@@ -2759,6 +2771,16 @@ interface PartialProfitContract {
|
|
|
2759
2771
|
* Identifies which market this profit event belongs to.
|
|
2760
2772
|
*/
|
|
2761
2773
|
symbol: string;
|
|
2774
|
+
/**
|
|
2775
|
+
* Strategy name that generated this signal.
|
|
2776
|
+
* Identifies which strategy execution this profit event belongs to.
|
|
2777
|
+
*/
|
|
2778
|
+
strategyName: string;
|
|
2779
|
+
/**
|
|
2780
|
+
* Exchange name where this signal is being executed.
|
|
2781
|
+
* Identifies which exchange this profit event belongs to.
|
|
2782
|
+
*/
|
|
2783
|
+
exchangeName: string;
|
|
2762
2784
|
/**
|
|
2763
2785
|
* Complete signal row data.
|
|
2764
2786
|
* Contains all signal information: id, position, priceOpen, priceTakeProfit, priceStopLoss, etc.
|
|
@@ -2844,6 +2866,16 @@ interface PartialLossContract {
|
|
|
2844
2866
|
* Identifies which market this loss event belongs to.
|
|
2845
2867
|
*/
|
|
2846
2868
|
symbol: string;
|
|
2869
|
+
/**
|
|
2870
|
+
* Strategy name that generated this signal.
|
|
2871
|
+
* Identifies which strategy execution this loss event belongs to.
|
|
2872
|
+
*/
|
|
2873
|
+
strategyName: string;
|
|
2874
|
+
/**
|
|
2875
|
+
* Exchange name where this signal is being executed.
|
|
2876
|
+
* Identifies which exchange this loss event belongs to.
|
|
2877
|
+
*/
|
|
2878
|
+
exchangeName: string;
|
|
2847
2879
|
/**
|
|
2848
2880
|
* Complete signal row data.
|
|
2849
2881
|
* Contains all signal information: id, position, priceOpen, priceTakeProfit, priceStopLoss, etc.
|
|
@@ -2896,6 +2928,95 @@ interface PartialLossContract {
|
|
|
2896
2928
|
timestamp: number;
|
|
2897
2929
|
}
|
|
2898
2930
|
|
|
2931
|
+
/**
|
|
2932
|
+
* Contract for risk rejection events.
|
|
2933
|
+
*
|
|
2934
|
+
* Emitted by riskSubject ONLY when a signal is REJECTED due to risk validation failure.
|
|
2935
|
+
* Used for tracking actual risk violations and monitoring rejected signals.
|
|
2936
|
+
*
|
|
2937
|
+
* Events are emitted only when risk limits are violated (not for allowed signals).
|
|
2938
|
+
* This prevents spam and allows focusing on actual risk management interventions.
|
|
2939
|
+
*
|
|
2940
|
+
* Consumers:
|
|
2941
|
+
* - RiskMarkdownService: Accumulates rejection events for report generation
|
|
2942
|
+
* - User callbacks via listenRisk() / listenRiskOnce()
|
|
2943
|
+
*
|
|
2944
|
+
* @example
|
|
2945
|
+
* ```typescript
|
|
2946
|
+
* import { listenRisk } from "backtest-kit";
|
|
2947
|
+
*
|
|
2948
|
+
* // Listen to all risk rejection events
|
|
2949
|
+
* listenRisk((event) => {
|
|
2950
|
+
* console.log(`[RISK REJECTED] Signal for ${event.symbol}`);
|
|
2951
|
+
* console.log(`Strategy: ${event.strategyName}`);
|
|
2952
|
+
* console.log(`Active positions: ${event.activePositionCount}`);
|
|
2953
|
+
* console.log(`Price: ${event.currentPrice}`);
|
|
2954
|
+
* console.log(`Timestamp: ${new Date(event.timestamp).toISOString()}`);
|
|
2955
|
+
* });
|
|
2956
|
+
*
|
|
2957
|
+
* // Alert on risk rejections for specific symbol
|
|
2958
|
+
* listenRisk((event) => {
|
|
2959
|
+
* if (event.symbol === "BTCUSDT") {
|
|
2960
|
+
* console.warn("BTC signal rejected due to risk limits!");
|
|
2961
|
+
* }
|
|
2962
|
+
* });
|
|
2963
|
+
* ```
|
|
2964
|
+
*/
|
|
2965
|
+
interface RiskContract {
|
|
2966
|
+
/**
|
|
2967
|
+
* Trading pair symbol (e.g., "BTCUSDT").
|
|
2968
|
+
* Identifies which market this rejected signal belongs to.
|
|
2969
|
+
*/
|
|
2970
|
+
symbol: string;
|
|
2971
|
+
/**
|
|
2972
|
+
* Pending signal to apply.
|
|
2973
|
+
* Contains signal details (position, priceOpen, priceTakeProfit, priceStopLoss, etc).
|
|
2974
|
+
*/
|
|
2975
|
+
pendingSignal: ISignalDto;
|
|
2976
|
+
/**
|
|
2977
|
+
* Strategy name requesting to open a position.
|
|
2978
|
+
* Identifies which strategy attempted to create the signal.
|
|
2979
|
+
*/
|
|
2980
|
+
strategyName: StrategyName;
|
|
2981
|
+
/**
|
|
2982
|
+
* Exchange name.
|
|
2983
|
+
* Identifies which exchange this signal was for.
|
|
2984
|
+
*/
|
|
2985
|
+
exchangeName: ExchangeName;
|
|
2986
|
+
/**
|
|
2987
|
+
* Current VWAP price at the time of rejection.
|
|
2988
|
+
* Market price when risk check was performed.
|
|
2989
|
+
*/
|
|
2990
|
+
currentPrice: number;
|
|
2991
|
+
/**
|
|
2992
|
+
* Number of currently active positions across all strategies at rejection time.
|
|
2993
|
+
* Used to track portfolio-level exposure when signal was rejected.
|
|
2994
|
+
*/
|
|
2995
|
+
activePositionCount: number;
|
|
2996
|
+
/**
|
|
2997
|
+
* Comment describing why the signal was rejected.
|
|
2998
|
+
* Captured from IRiskValidation.note or "N/A" if not provided.
|
|
2999
|
+
*
|
|
3000
|
+
* @example
|
|
3001
|
+
* ```typescript
|
|
3002
|
+
* console.log(`Rejection reason: ${event.comment}`);
|
|
3003
|
+
* // Output: "Rejection reason: Max 3 positions allowed"
|
|
3004
|
+
* ```
|
|
3005
|
+
*/
|
|
3006
|
+
comment: string;
|
|
3007
|
+
/**
|
|
3008
|
+
* Event timestamp in milliseconds since Unix epoch.
|
|
3009
|
+
* Represents when the signal was rejected.
|
|
3010
|
+
*
|
|
3011
|
+
* @example
|
|
3012
|
+
* ```typescript
|
|
3013
|
+
* const eventDate = new Date(event.timestamp);
|
|
3014
|
+
* console.log(`Signal rejected at: ${eventDate.toISOString()}`);
|
|
3015
|
+
* ```
|
|
3016
|
+
*/
|
|
3017
|
+
timestamp: number;
|
|
3018
|
+
}
|
|
3019
|
+
|
|
2899
3020
|
/**
|
|
2900
3021
|
* Subscribes to all signal events with queued async processing.
|
|
2901
3022
|
*
|
|
@@ -3616,6 +3737,69 @@ declare function listenPartialLoss(fn: (event: PartialLossContract) => void): ()
|
|
|
3616
3737
|
* ```
|
|
3617
3738
|
*/
|
|
3618
3739
|
declare function listenPartialLossOnce(filterFn: (event: PartialLossContract) => boolean, fn: (event: PartialLossContract) => void): () => void;
|
|
3740
|
+
/**
|
|
3741
|
+
* Subscribes to risk rejection events with queued async processing.
|
|
3742
|
+
*
|
|
3743
|
+
* Emits ONLY when a signal is rejected due to risk validation failure.
|
|
3744
|
+
* Does not emit for allowed signals (prevents spam).
|
|
3745
|
+
* Events are processed sequentially in order received, even if callback is async.
|
|
3746
|
+
* Uses queued wrapper to prevent concurrent execution of the callback.
|
|
3747
|
+
*
|
|
3748
|
+
* @param fn - Callback function to handle risk rejection events
|
|
3749
|
+
* @returns Unsubscribe function to stop listening to events
|
|
3750
|
+
*
|
|
3751
|
+
* @example
|
|
3752
|
+
* ```typescript
|
|
3753
|
+
* import { listenRisk } from "./function/event";
|
|
3754
|
+
*
|
|
3755
|
+
* const unsubscribe = listenRisk((event) => {
|
|
3756
|
+
* console.log(`[RISK REJECTED] Signal for ${event.symbol}`);
|
|
3757
|
+
* console.log(`Strategy: ${event.strategyName}`);
|
|
3758
|
+
* console.log(`Position: ${event.pendingSignal.position}`);
|
|
3759
|
+
* console.log(`Active positions: ${event.activePositionCount}`);
|
|
3760
|
+
* console.log(`Reason: ${event.comment}`);
|
|
3761
|
+
* console.log(`Price: ${event.currentPrice}`);
|
|
3762
|
+
* });
|
|
3763
|
+
*
|
|
3764
|
+
* // Later: stop listening
|
|
3765
|
+
* unsubscribe();
|
|
3766
|
+
* ```
|
|
3767
|
+
*/
|
|
3768
|
+
declare function listenRisk(fn: (event: RiskContract) => void): () => void;
|
|
3769
|
+
/**
|
|
3770
|
+
* Subscribes to filtered risk rejection events with one-time execution.
|
|
3771
|
+
*
|
|
3772
|
+
* Listens for events matching the filter predicate, then executes callback once
|
|
3773
|
+
* and automatically unsubscribes. Useful for waiting for specific risk rejection conditions.
|
|
3774
|
+
*
|
|
3775
|
+
* @param filterFn - Predicate to filter which events trigger the callback
|
|
3776
|
+
* @param fn - Callback function to handle the filtered event (called only once)
|
|
3777
|
+
* @returns Unsubscribe function to cancel the listener before it fires
|
|
3778
|
+
*
|
|
3779
|
+
* @example
|
|
3780
|
+
* ```typescript
|
|
3781
|
+
* import { listenRiskOnce } from "./function/event";
|
|
3782
|
+
*
|
|
3783
|
+
* // Wait for first risk rejection on BTCUSDT
|
|
3784
|
+
* listenRiskOnce(
|
|
3785
|
+
* (event) => event.symbol === "BTCUSDT",
|
|
3786
|
+
* (event) => {
|
|
3787
|
+
* console.log("BTCUSDT signal rejected!");
|
|
3788
|
+
* console.log("Reason:", event.comment);
|
|
3789
|
+
* }
|
|
3790
|
+
* );
|
|
3791
|
+
*
|
|
3792
|
+
* // Wait for rejection due to position limit
|
|
3793
|
+
* const cancel = listenRiskOnce(
|
|
3794
|
+
* (event) => event.comment.includes("Max") && event.activePositionCount >= 3,
|
|
3795
|
+
* (event) => console.log("Position limit reached:", event.activePositionCount)
|
|
3796
|
+
* );
|
|
3797
|
+
*
|
|
3798
|
+
* // Cancel if needed before event fires
|
|
3799
|
+
* cancel();
|
|
3800
|
+
* ```
|
|
3801
|
+
*/
|
|
3802
|
+
declare function listenRiskOnce(filterFn: (event: RiskContract) => boolean, fn: (event: RiskContract) => void): () => void;
|
|
3619
3803
|
|
|
3620
3804
|
/**
|
|
3621
3805
|
* Fetches historical candle data from the registered exchange.
|
|
@@ -4787,6 +4971,182 @@ declare class PartialMarkdownService {
|
|
|
4787
4971
|
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
4788
4972
|
}
|
|
4789
4973
|
|
|
4974
|
+
/**
|
|
4975
|
+
* Risk rejection event data for report generation.
|
|
4976
|
+
* Contains all information about rejected signals due to risk limits.
|
|
4977
|
+
*/
|
|
4978
|
+
interface RiskEvent {
|
|
4979
|
+
/** Event timestamp in milliseconds */
|
|
4980
|
+
timestamp: number;
|
|
4981
|
+
/** Trading pair symbol */
|
|
4982
|
+
symbol: string;
|
|
4983
|
+
/** Pending signal details */
|
|
4984
|
+
pendingSignal: ISignalDto;
|
|
4985
|
+
/** Strategy name */
|
|
4986
|
+
strategyName: string;
|
|
4987
|
+
/** Exchange name */
|
|
4988
|
+
exchangeName: string;
|
|
4989
|
+
/** Current market price */
|
|
4990
|
+
currentPrice: number;
|
|
4991
|
+
/** Number of active positions at rejection time */
|
|
4992
|
+
activePositionCount: number;
|
|
4993
|
+
/** Rejection reason from validation note */
|
|
4994
|
+
comment: string;
|
|
4995
|
+
}
|
|
4996
|
+
/**
|
|
4997
|
+
* Statistical data calculated from risk rejection events.
|
|
4998
|
+
*
|
|
4999
|
+
* Provides metrics for risk management tracking.
|
|
5000
|
+
*
|
|
5001
|
+
* @example
|
|
5002
|
+
* ```typescript
|
|
5003
|
+
* const stats = await Risk.getData("BTCUSDT", "my-strategy");
|
|
5004
|
+
*
|
|
5005
|
+
* console.log(`Total rejections: ${stats.totalRejections}`);
|
|
5006
|
+
* console.log(`Rejections by symbol:`, stats.bySymbol);
|
|
5007
|
+
* ```
|
|
5008
|
+
*/
|
|
5009
|
+
interface RiskStatistics {
|
|
5010
|
+
/** Array of all risk rejection events with full details */
|
|
5011
|
+
eventList: RiskEvent[];
|
|
5012
|
+
/** Total number of risk rejections */
|
|
5013
|
+
totalRejections: number;
|
|
5014
|
+
/** Rejections grouped by symbol */
|
|
5015
|
+
bySymbol: Record<string, number>;
|
|
5016
|
+
/** Rejections grouped by strategy */
|
|
5017
|
+
byStrategy: Record<string, number>;
|
|
5018
|
+
}
|
|
5019
|
+
/**
|
|
5020
|
+
* Service for generating and saving risk rejection markdown reports.
|
|
5021
|
+
*
|
|
5022
|
+
* Features:
|
|
5023
|
+
* - Listens to risk rejection events via riskSubject
|
|
5024
|
+
* - Accumulates all rejection events per symbol-strategy pair
|
|
5025
|
+
* - Generates markdown tables with detailed rejection information
|
|
5026
|
+
* - Provides statistics (total rejections, by symbol, by strategy)
|
|
5027
|
+
* - Saves reports to disk in dump/risk/{symbol}_{strategyName}.md
|
|
5028
|
+
*
|
|
5029
|
+
* @example
|
|
5030
|
+
* ```typescript
|
|
5031
|
+
* const service = new RiskMarkdownService();
|
|
5032
|
+
*
|
|
5033
|
+
* // Service automatically subscribes to subjects on init
|
|
5034
|
+
* // No manual callback setup needed
|
|
5035
|
+
*
|
|
5036
|
+
* // Later: generate and save report
|
|
5037
|
+
* await service.dump("BTCUSDT", "my-strategy");
|
|
5038
|
+
* ```
|
|
5039
|
+
*/
|
|
5040
|
+
declare class RiskMarkdownService {
|
|
5041
|
+
/** Logger service for debug output */
|
|
5042
|
+
private readonly loggerService;
|
|
5043
|
+
/**
|
|
5044
|
+
* Memoized function to get or create ReportStorage for a symbol-strategy pair.
|
|
5045
|
+
* Each symbol-strategy combination gets its own isolated storage instance.
|
|
5046
|
+
*/
|
|
5047
|
+
private getStorage;
|
|
5048
|
+
/**
|
|
5049
|
+
* Processes risk rejection events and accumulates them.
|
|
5050
|
+
* Should be called from riskSubject subscription.
|
|
5051
|
+
*
|
|
5052
|
+
* @param data - Risk rejection event data
|
|
5053
|
+
*
|
|
5054
|
+
* @example
|
|
5055
|
+
* ```typescript
|
|
5056
|
+
* const service = new RiskMarkdownService();
|
|
5057
|
+
* // Service automatically subscribes in init()
|
|
5058
|
+
* ```
|
|
5059
|
+
*/
|
|
5060
|
+
private tickRejection;
|
|
5061
|
+
/**
|
|
5062
|
+
* Gets statistical data from all risk rejection events for a symbol-strategy pair.
|
|
5063
|
+
* Delegates to ReportStorage.getData().
|
|
5064
|
+
*
|
|
5065
|
+
* @param symbol - Trading pair symbol to get data for
|
|
5066
|
+
* @param strategyName - Strategy name to get data for
|
|
5067
|
+
* @returns Statistical data object with all metrics
|
|
5068
|
+
*
|
|
5069
|
+
* @example
|
|
5070
|
+
* ```typescript
|
|
5071
|
+
* const service = new RiskMarkdownService();
|
|
5072
|
+
* const stats = await service.getData("BTCUSDT", "my-strategy");
|
|
5073
|
+
* console.log(stats.totalRejections, stats.bySymbol);
|
|
5074
|
+
* ```
|
|
5075
|
+
*/
|
|
5076
|
+
getData: (symbol: string, strategyName: string) => Promise<RiskStatistics>;
|
|
5077
|
+
/**
|
|
5078
|
+
* Generates markdown report with all risk rejection events for a symbol-strategy pair.
|
|
5079
|
+
* Delegates to ReportStorage.getReport().
|
|
5080
|
+
*
|
|
5081
|
+
* @param symbol - Trading pair symbol to generate report for
|
|
5082
|
+
* @param strategyName - Strategy name to generate report for
|
|
5083
|
+
* @returns Markdown formatted report string with table of all events
|
|
5084
|
+
*
|
|
5085
|
+
* @example
|
|
5086
|
+
* ```typescript
|
|
5087
|
+
* const service = new RiskMarkdownService();
|
|
5088
|
+
* const markdown = await service.getReport("BTCUSDT", "my-strategy");
|
|
5089
|
+
* console.log(markdown);
|
|
5090
|
+
* ```
|
|
5091
|
+
*/
|
|
5092
|
+
getReport: (symbol: string, strategyName: string) => Promise<string>;
|
|
5093
|
+
/**
|
|
5094
|
+
* Saves symbol-strategy report to disk.
|
|
5095
|
+
* Creates directory if it doesn't exist.
|
|
5096
|
+
* Delegates to ReportStorage.dump().
|
|
5097
|
+
*
|
|
5098
|
+
* @param symbol - Trading pair symbol to save report for
|
|
5099
|
+
* @param strategyName - Strategy name to save report for
|
|
5100
|
+
* @param path - Directory path to save report (default: "./dump/risk")
|
|
5101
|
+
*
|
|
5102
|
+
* @example
|
|
5103
|
+
* ```typescript
|
|
5104
|
+
* const service = new RiskMarkdownService();
|
|
5105
|
+
*
|
|
5106
|
+
* // Save to default path: ./dump/risk/BTCUSDT_my-strategy.md
|
|
5107
|
+
* await service.dump("BTCUSDT", "my-strategy");
|
|
5108
|
+
*
|
|
5109
|
+
* // Save to custom path: ./custom/path/BTCUSDT_my-strategy.md
|
|
5110
|
+
* await service.dump("BTCUSDT", "my-strategy", "./custom/path");
|
|
5111
|
+
* ```
|
|
5112
|
+
*/
|
|
5113
|
+
dump: (symbol: string, strategyName: string, path?: string) => Promise<void>;
|
|
5114
|
+
/**
|
|
5115
|
+
* Clears accumulated event data from storage.
|
|
5116
|
+
* If ctx is provided, clears only that specific symbol-strategy pair's data.
|
|
5117
|
+
* If nothing is provided, clears all data.
|
|
5118
|
+
*
|
|
5119
|
+
* @param ctx - Optional context with symbol and strategyName
|
|
5120
|
+
*
|
|
5121
|
+
* @example
|
|
5122
|
+
* ```typescript
|
|
5123
|
+
* const service = new RiskMarkdownService();
|
|
5124
|
+
*
|
|
5125
|
+
* // Clear specific symbol-strategy pair
|
|
5126
|
+
* await service.clear({ symbol: "BTCUSDT", strategyName: "my-strategy" });
|
|
5127
|
+
*
|
|
5128
|
+
* // Clear all data
|
|
5129
|
+
* await service.clear();
|
|
5130
|
+
* ```
|
|
5131
|
+
*/
|
|
5132
|
+
clear: (ctx?: {
|
|
5133
|
+
symbol: string;
|
|
5134
|
+
strategyName: string;
|
|
5135
|
+
}) => Promise<void>;
|
|
5136
|
+
/**
|
|
5137
|
+
* Initializes the service by subscribing to risk rejection events.
|
|
5138
|
+
* Uses singleshot to ensure initialization happens only once.
|
|
5139
|
+
* Automatically called on first use.
|
|
5140
|
+
*
|
|
5141
|
+
* @example
|
|
5142
|
+
* ```typescript
|
|
5143
|
+
* const service = new RiskMarkdownService();
|
|
5144
|
+
* await service.init(); // Subscribe to rejection events
|
|
5145
|
+
* ```
|
|
5146
|
+
*/
|
|
5147
|
+
protected init: (() => Promise<void>) & functools_kit.ISingleshotClearable;
|
|
5148
|
+
}
|
|
5149
|
+
|
|
4790
5150
|
declare const BASE_WAIT_FOR_INIT_SYMBOL: unique symbol;
|
|
4791
5151
|
/**
|
|
4792
5152
|
* Signal data stored in persistence layer.
|
|
@@ -6444,6 +6804,157 @@ declare class ConstantUtils {
|
|
|
6444
6804
|
*/
|
|
6445
6805
|
declare const Constant: ConstantUtils;
|
|
6446
6806
|
|
|
6807
|
+
/**
|
|
6808
|
+
* Utility class for accessing risk rejection reports and statistics.
|
|
6809
|
+
*
|
|
6810
|
+
* Provides static-like methods (via singleton instance) to retrieve data
|
|
6811
|
+
* accumulated by RiskMarkdownService from risk rejection events.
|
|
6812
|
+
*
|
|
6813
|
+
* Features:
|
|
6814
|
+
* - Statistical data extraction (total rejections count, by symbol, by strategy)
|
|
6815
|
+
* - Markdown report generation with event tables
|
|
6816
|
+
* - File export to disk
|
|
6817
|
+
*
|
|
6818
|
+
* Data source:
|
|
6819
|
+
* - RiskMarkdownService listens to riskSubject
|
|
6820
|
+
* - Accumulates rejection events in ReportStorage (max 250 events per symbol-strategy pair)
|
|
6821
|
+
* - Events include: timestamp, symbol, strategyName, position, exchangeName, price, activePositionCount, comment
|
|
6822
|
+
*
|
|
6823
|
+
* @example
|
|
6824
|
+
* ```typescript
|
|
6825
|
+
* import { Risk } from "./classes/Risk";
|
|
6826
|
+
*
|
|
6827
|
+
* // Get statistical data for BTCUSDT:my-strategy
|
|
6828
|
+
* const stats = await Risk.getData("BTCUSDT", "my-strategy");
|
|
6829
|
+
* console.log(`Total rejections: ${stats.totalRejections}`);
|
|
6830
|
+
* console.log(`By symbol:`, stats.bySymbol);
|
|
6831
|
+
* console.log(`By strategy:`, stats.byStrategy);
|
|
6832
|
+
*
|
|
6833
|
+
* // Generate markdown report
|
|
6834
|
+
* const markdown = await Risk.getReport("BTCUSDT", "my-strategy");
|
|
6835
|
+
* console.log(markdown); // Formatted table with all rejection events
|
|
6836
|
+
*
|
|
6837
|
+
* // Export report to file
|
|
6838
|
+
* await Risk.dump("BTCUSDT", "my-strategy"); // Saves to ./dump/risk/BTCUSDT_my-strategy.md
|
|
6839
|
+
* await Risk.dump("BTCUSDT", "my-strategy", "./custom/path"); // Custom directory
|
|
6840
|
+
* ```
|
|
6841
|
+
*/
|
|
6842
|
+
declare class RiskUtils {
|
|
6843
|
+
/**
|
|
6844
|
+
* Retrieves statistical data from accumulated risk rejection events.
|
|
6845
|
+
*
|
|
6846
|
+
* Delegates to RiskMarkdownService.getData() which reads from ReportStorage.
|
|
6847
|
+
* Returns aggregated metrics calculated from all rejection events.
|
|
6848
|
+
*
|
|
6849
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
6850
|
+
* @param strategyName - Strategy name (e.g., "my-strategy")
|
|
6851
|
+
* @returns Promise resolving to RiskStatistics object with counts and event list
|
|
6852
|
+
*
|
|
6853
|
+
* @example
|
|
6854
|
+
* ```typescript
|
|
6855
|
+
* const stats = await Risk.getData("BTCUSDT", "my-strategy");
|
|
6856
|
+
*
|
|
6857
|
+
* console.log(`Total rejections: ${stats.totalRejections}`);
|
|
6858
|
+
* console.log(`Rejections by symbol:`, stats.bySymbol);
|
|
6859
|
+
* console.log(`Rejections by strategy:`, stats.byStrategy);
|
|
6860
|
+
*
|
|
6861
|
+
* // Iterate through all rejection events
|
|
6862
|
+
* for (const event of stats.eventList) {
|
|
6863
|
+
* console.log(`REJECTED: ${event.symbol} - ${event.comment} (${event.activePositionCount} active)`);
|
|
6864
|
+
* }
|
|
6865
|
+
* ```
|
|
6866
|
+
*/
|
|
6867
|
+
getData: (symbol: string, strategyName: string) => Promise<RiskStatistics>;
|
|
6868
|
+
/**
|
|
6869
|
+
* Generates markdown report with all risk rejection events for a symbol-strategy pair.
|
|
6870
|
+
*
|
|
6871
|
+
* Creates formatted table containing:
|
|
6872
|
+
* - Symbol
|
|
6873
|
+
* - Strategy
|
|
6874
|
+
* - Position (LONG/SHORT)
|
|
6875
|
+
* - Exchange
|
|
6876
|
+
* - Price
|
|
6877
|
+
* - Active Positions (at rejection time)
|
|
6878
|
+
* - Reason (from validation note)
|
|
6879
|
+
* - Timestamp (ISO 8601)
|
|
6880
|
+
*
|
|
6881
|
+
* Also includes summary statistics at the end (total rejections, by symbol, by strategy).
|
|
6882
|
+
*
|
|
6883
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
6884
|
+
* @param strategyName - Strategy name (e.g., "my-strategy")
|
|
6885
|
+
* @returns Promise resolving to markdown formatted report string
|
|
6886
|
+
*
|
|
6887
|
+
* @example
|
|
6888
|
+
* ```typescript
|
|
6889
|
+
* const markdown = await Risk.getReport("BTCUSDT", "my-strategy");
|
|
6890
|
+
* console.log(markdown);
|
|
6891
|
+
*
|
|
6892
|
+
* // Output:
|
|
6893
|
+
* // # Risk Rejection Report: BTCUSDT:my-strategy
|
|
6894
|
+
* //
|
|
6895
|
+
* // | Symbol | Strategy | Position | Exchange | Price | Active Positions | Reason | Timestamp |
|
|
6896
|
+
* // | --- | --- | --- | --- | --- | --- | --- | --- |
|
|
6897
|
+
* // | BTCUSDT | my-strategy | LONG | binance | 50000.00000000 USD | 3 | Max 3 positions allowed | 2024-01-15T10:30:00.000Z |
|
|
6898
|
+
* //
|
|
6899
|
+
* // **Total rejections:** 1
|
|
6900
|
+
* //
|
|
6901
|
+
* // ## Rejections by Symbol
|
|
6902
|
+
* // - BTCUSDT: 1
|
|
6903
|
+
* //
|
|
6904
|
+
* // ## Rejections by Strategy
|
|
6905
|
+
* // - my-strategy: 1
|
|
6906
|
+
* ```
|
|
6907
|
+
*/
|
|
6908
|
+
getReport: (symbol: string, strategyName: string) => Promise<string>;
|
|
6909
|
+
/**
|
|
6910
|
+
* Generates and saves markdown report to file.
|
|
6911
|
+
*
|
|
6912
|
+
* Creates directory if it doesn't exist.
|
|
6913
|
+
* Filename format: {symbol}_{strategyName}.md (e.g., "BTCUSDT_my-strategy.md")
|
|
6914
|
+
*
|
|
6915
|
+
* Delegates to RiskMarkdownService.dump() which:
|
|
6916
|
+
* 1. Generates markdown report via getReport()
|
|
6917
|
+
* 2. Creates output directory (recursive mkdir)
|
|
6918
|
+
* 3. Writes file with UTF-8 encoding
|
|
6919
|
+
* 4. Logs success/failure to console
|
|
6920
|
+
*
|
|
6921
|
+
* @param symbol - Trading pair symbol (e.g., "BTCUSDT")
|
|
6922
|
+
* @param strategyName - Strategy name (e.g., "my-strategy")
|
|
6923
|
+
* @param path - Output directory path (default: "./dump/risk")
|
|
6924
|
+
* @returns Promise that resolves when file is written
|
|
6925
|
+
*
|
|
6926
|
+
* @example
|
|
6927
|
+
* ```typescript
|
|
6928
|
+
* // Save to default path: ./dump/risk/BTCUSDT_my-strategy.md
|
|
6929
|
+
* await Risk.dump("BTCUSDT", "my-strategy");
|
|
6930
|
+
*
|
|
6931
|
+
* // Save to custom path: ./reports/risk/BTCUSDT_my-strategy.md
|
|
6932
|
+
* await Risk.dump("BTCUSDT", "my-strategy", "./reports/risk");
|
|
6933
|
+
*
|
|
6934
|
+
* // After multiple symbols backtested, export all risk reports
|
|
6935
|
+
* for (const symbol of ["BTCUSDT", "ETHUSDT", "BNBUSDT"]) {
|
|
6936
|
+
* await Risk.dump(symbol, "my-strategy", "./backtest-results");
|
|
6937
|
+
* }
|
|
6938
|
+
* ```
|
|
6939
|
+
*/
|
|
6940
|
+
dump: (symbol: string, strategyName: string, path?: string) => Promise<void>;
|
|
6941
|
+
}
|
|
6942
|
+
/**
|
|
6943
|
+
* Global singleton instance of RiskUtils.
|
|
6944
|
+
* Provides static-like access to risk rejection reporting methods.
|
|
6945
|
+
*
|
|
6946
|
+
* @example
|
|
6947
|
+
* ```typescript
|
|
6948
|
+
* import { Risk } from "backtest-kit";
|
|
6949
|
+
*
|
|
6950
|
+
* // Usage same as RiskUtils methods
|
|
6951
|
+
* const stats = await Risk.getData("BTCUSDT", "my-strategy");
|
|
6952
|
+
* const report = await Risk.getReport("BTCUSDT", "my-strategy");
|
|
6953
|
+
* await Risk.dump("BTCUSDT", "my-strategy");
|
|
6954
|
+
* ```
|
|
6955
|
+
*/
|
|
6956
|
+
declare const Risk: RiskUtils;
|
|
6957
|
+
|
|
6447
6958
|
/**
|
|
6448
6959
|
* Contract for walker stop signal events.
|
|
6449
6960
|
*
|
|
@@ -6567,6 +7078,12 @@ declare const partialProfitSubject: Subject<PartialProfitContract>;
|
|
|
6567
7078
|
* Emits when a signal reaches a loss level (10%, 20%, 30%, etc).
|
|
6568
7079
|
*/
|
|
6569
7080
|
declare const partialLossSubject: Subject<PartialLossContract>;
|
|
7081
|
+
/**
|
|
7082
|
+
* Risk rejection emitter for risk management violations.
|
|
7083
|
+
* Emits ONLY when a signal is rejected due to risk validation failure.
|
|
7084
|
+
* Does not emit for allowed signals (prevents spam).
|
|
7085
|
+
*/
|
|
7086
|
+
declare const riskSubject: Subject<RiskContract>;
|
|
6570
7087
|
|
|
6571
7088
|
declare const emitters_doneBacktestSubject: typeof doneBacktestSubject;
|
|
6572
7089
|
declare const emitters_doneLiveSubject: typeof doneLiveSubject;
|
|
@@ -6579,6 +7096,7 @@ declare const emitters_performanceEmitter: typeof performanceEmitter;
|
|
|
6579
7096
|
declare const emitters_progressBacktestEmitter: typeof progressBacktestEmitter;
|
|
6580
7097
|
declare const emitters_progressOptimizerEmitter: typeof progressOptimizerEmitter;
|
|
6581
7098
|
declare const emitters_progressWalkerEmitter: typeof progressWalkerEmitter;
|
|
7099
|
+
declare const emitters_riskSubject: typeof riskSubject;
|
|
6582
7100
|
declare const emitters_signalBacktestEmitter: typeof signalBacktestEmitter;
|
|
6583
7101
|
declare const emitters_signalEmitter: typeof signalEmitter;
|
|
6584
7102
|
declare const emitters_signalLiveEmitter: typeof signalLiveEmitter;
|
|
@@ -6587,7 +7105,7 @@ declare const emitters_walkerCompleteSubject: typeof walkerCompleteSubject;
|
|
|
6587
7105
|
declare const emitters_walkerEmitter: typeof walkerEmitter;
|
|
6588
7106
|
declare const emitters_walkerStopSubject: typeof walkerStopSubject;
|
|
6589
7107
|
declare namespace emitters {
|
|
6590
|
-
export { emitters_doneBacktestSubject as doneBacktestSubject, emitters_doneLiveSubject as doneLiveSubject, emitters_doneWalkerSubject as doneWalkerSubject, emitters_errorEmitter as errorEmitter, emitters_exitEmitter as exitEmitter, emitters_partialLossSubject as partialLossSubject, emitters_partialProfitSubject as partialProfitSubject, emitters_performanceEmitter as performanceEmitter, emitters_progressBacktestEmitter as progressBacktestEmitter, emitters_progressOptimizerEmitter as progressOptimizerEmitter, emitters_progressWalkerEmitter as progressWalkerEmitter, emitters_signalBacktestEmitter as signalBacktestEmitter, emitters_signalEmitter as signalEmitter, emitters_signalLiveEmitter as signalLiveEmitter, emitters_validationSubject as validationSubject, emitters_walkerCompleteSubject as walkerCompleteSubject, emitters_walkerEmitter as walkerEmitter, emitters_walkerStopSubject as walkerStopSubject };
|
|
7108
|
+
export { emitters_doneBacktestSubject as doneBacktestSubject, emitters_doneLiveSubject as doneLiveSubject, emitters_doneWalkerSubject as doneWalkerSubject, emitters_errorEmitter as errorEmitter, emitters_exitEmitter as exitEmitter, emitters_partialLossSubject as partialLossSubject, emitters_partialProfitSubject as partialProfitSubject, emitters_performanceEmitter as performanceEmitter, emitters_progressBacktestEmitter as progressBacktestEmitter, emitters_progressOptimizerEmitter as progressOptimizerEmitter, emitters_progressWalkerEmitter as progressWalkerEmitter, emitters_riskSubject as riskSubject, emitters_signalBacktestEmitter as signalBacktestEmitter, emitters_signalEmitter as signalEmitter, emitters_signalLiveEmitter as signalLiveEmitter, emitters_validationSubject as validationSubject, emitters_walkerCompleteSubject as walkerCompleteSubject, emitters_walkerEmitter as walkerEmitter, emitters_walkerStopSubject as walkerStopSubject };
|
|
6591
7109
|
}
|
|
6592
7110
|
|
|
6593
7111
|
/**
|
|
@@ -7210,6 +7728,7 @@ declare class RiskConnectionService {
|
|
|
7210
7728
|
*
|
|
7211
7729
|
* Routes to appropriate ClientRisk instance based on provided context.
|
|
7212
7730
|
* Validates portfolio drawdown, symbol exposure, position count, and daily loss limits.
|
|
7731
|
+
* ClientRisk will emit riskSubject event via onRejected callback when signal is rejected.
|
|
7213
7732
|
*
|
|
7214
7733
|
* @param params - Risk check arguments (portfolio state, position details)
|
|
7215
7734
|
* @param context - Execution context with risk name
|
|
@@ -9312,6 +9831,7 @@ declare const backtest: {
|
|
|
9312
9831
|
heatMarkdownService: HeatMarkdownService;
|
|
9313
9832
|
partialMarkdownService: PartialMarkdownService;
|
|
9314
9833
|
outlineMarkdownService: OutlineMarkdownService;
|
|
9834
|
+
riskMarkdownService: RiskMarkdownService;
|
|
9315
9835
|
backtestLogicPublicService: BacktestLogicPublicService;
|
|
9316
9836
|
liveLogicPublicService: LiveLogicPublicService;
|
|
9317
9837
|
walkerLogicPublicService: WalkerLogicPublicService;
|
|
@@ -9351,4 +9871,4 @@ declare const backtest: {
|
|
|
9351
9871
|
loggerService: LoggerService;
|
|
9352
9872
|
};
|
|
9353
9873
|
|
|
9354
|
-
export { Backtest, type BacktestStatistics, type CandleInterval, Constant, type DoneContract, type EntityId, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IHeatmapStatistics, type IOptimizerCallbacks, type IOptimizerData, type IOptimizerFetchArgs, type IOptimizerFilterArgs, type IOptimizerRange, type IOptimizerSchema, type IOptimizerSource, type IOptimizerStrategy, type IOptimizerTemplate, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskValidation, type IRiskValidationFn, type IRiskValidationPayload, type IScheduledSignalRow, type ISignalDto, type ISignalRow, type ISizingCalculateParams, type ISizingCalculateParamsATR, type ISizingCalculateParamsFixedPercentage, type ISizingCalculateParamsKelly, type ISizingSchema, type ISizingSchemaATR, type ISizingSchemaFixedPercentage, type ISizingSchemaKelly, type IStrategyPnL, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, Live, type LiveStatistics, type MessageModel, type MessageRole, MethodContextService, Optimizer, Partial$1 as Partial, type PartialData, type PartialLossContract, type PartialProfitContract, type PartialStatistics, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatistics, PersistBase, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PositionSize, type ProgressBacktestContract, type ProgressOptimizerContract, type ProgressWalkerContract, type RiskData, Schedule, type ScheduleData, type ScheduleStatistics, type SignalData, type SignalInterval, type TPersistBase, type TPersistBaseCtor, Walker, type WalkerContract, type WalkerMetric, type WalkerStatistics, addExchange, addFrame, addOptimizer, addRisk, addSizing, addStrategy, addWalker, dumpSignal, emitters, formatPrice, formatQuantity, getAveragePrice, getCandles, getConfig, getDate, getDefaultConfig, getMode, backtest as lib, listExchanges, listFrames, listOptimizers, listRisks, listSizings, listStrategies, listWalkers, listenBacktestProgress, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenOptimizerProgress, listenPartialLoss, listenPartialLossOnce, listenPartialProfit, listenPartialProfitOnce, listenPerformance, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, setConfig, setLogger };
|
|
9874
|
+
export { Backtest, type BacktestStatistics, type CandleInterval, Constant, type DoneContract, type EntityId, ExecutionContextService, type FrameInterval, type GlobalConfig, Heat, type ICandleData, type IExchangeSchema, type IFrameSchema, type IHeatmapRow, type IHeatmapStatistics, type IOptimizerCallbacks, type IOptimizerData, type IOptimizerFetchArgs, type IOptimizerFilterArgs, type IOptimizerRange, type IOptimizerSchema, type IOptimizerSource, type IOptimizerStrategy, type IOptimizerTemplate, type IPersistBase, type IPositionSizeATRParams, type IPositionSizeFixedPercentageParams, type IPositionSizeKellyParams, type IRiskActivePosition, type IRiskCheckArgs, type IRiskSchema, type IRiskValidation, type IRiskValidationFn, type IRiskValidationPayload, type IScheduledSignalRow, type ISignalDto, type ISignalRow, type ISizingCalculateParams, type ISizingCalculateParamsATR, type ISizingCalculateParamsFixedPercentage, type ISizingCalculateParamsKelly, type ISizingSchema, type ISizingSchemaATR, type ISizingSchemaFixedPercentage, type ISizingSchemaKelly, type IStrategyPnL, type IStrategySchema, type IStrategyTickResult, type IStrategyTickResultActive, type IStrategyTickResultCancelled, type IStrategyTickResultClosed, type IStrategyTickResultIdle, type IStrategyTickResultOpened, type IStrategyTickResultScheduled, type IWalkerResults, type IWalkerSchema, type IWalkerStrategyResult, Live, type LiveStatistics, type MessageModel, type MessageRole, MethodContextService, Optimizer, Partial$1 as Partial, type PartialData, type PartialLossContract, type PartialProfitContract, type PartialStatistics, Performance, type PerformanceContract, type PerformanceMetricType, type PerformanceStatistics, PersistBase, PersistPartialAdapter, PersistRiskAdapter, PersistScheduleAdapter, PersistSignalAdapter, PositionSize, type ProgressBacktestContract, type ProgressOptimizerContract, type ProgressWalkerContract, Risk, type RiskContract, type RiskData, type RiskStatistics, Schedule, type ScheduleData, type ScheduleStatistics, type SignalData, type SignalInterval, type TPersistBase, type TPersistBaseCtor, Walker, type WalkerContract, type WalkerMetric, type WalkerStatistics, addExchange, addFrame, addOptimizer, addRisk, addSizing, addStrategy, addWalker, dumpSignal, emitters, formatPrice, formatQuantity, getAveragePrice, getCandles, getConfig, getDate, getDefaultConfig, getMode, backtest as lib, listExchanges, listFrames, listOptimizers, listRisks, listSizings, listStrategies, listWalkers, listenBacktestProgress, listenDoneBacktest, listenDoneBacktestOnce, listenDoneLive, listenDoneLiveOnce, listenDoneWalker, listenDoneWalkerOnce, listenError, listenExit, listenOptimizerProgress, listenPartialLoss, listenPartialLossOnce, listenPartialProfit, listenPartialProfitOnce, listenPerformance, listenRisk, listenRiskOnce, listenSignal, listenSignalBacktest, listenSignalBacktestOnce, listenSignalLive, listenSignalLiveOnce, listenSignalOnce, listenValidation, listenWalker, listenWalkerComplete, listenWalkerOnce, listenWalkerProgress, setConfig, setLogger };
|