From ae2c184633dfbd3f9a2c97071553bd5cf02fa890 Mon Sep 17 00:00:00 2001 From: Seungwoo321 Date: Mon, 18 Jul 2022 16:37:12 +0900 Subject: [PATCH 1/2] feat: add including fee in backtest --- src/lib/backtest.ts | 18 ++++++++++++------ src/lib/strategy.ts | 12 ++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/lib/backtest.ts b/src/lib/backtest.ts index b6cca7d..0a247d9 100644 --- a/src/lib/backtest.ts +++ b/src/lib/backtest.ts @@ -35,10 +35,13 @@ function updatePosition(position: IPosition, bar: IBar): void { * @param exitTime The timestamp for the bar when the position was exited. * @param exitPrice The price of the instrument when the position was exited. */ -function finalizePosition(position: IPosition, exitTime: Date, exitPrice: number, exitReason: string): ITrade { +function finalizePosition(position: IPosition, exitTime: Date, exitPrice: number, exitReason: string, fees: number): ITrade { const profit = position.direction === TradeDirection.Long ? exitPrice - position.entryPrice : position.entryPrice - exitPrice; + const growth = position.direction === TradeDirection.Long + ? exitPrice / position.entryPrice + : position.entryPrice / exitPrice; let rmultiple; if (position.initialUnitRisk !== undefined) { rmultiple = profit / position.initialUnitRisk; @@ -51,9 +54,7 @@ function finalizePosition(position: IPosition, exitTime: Date, exitPrice: number exitPrice: exitPrice, profit: profit, profitPct: (profit / position.entryPrice) * 100, - growth: position.direction === TradeDirection.Long - ? exitPrice / position.entryPrice - : position.entryPrice / exitPrice, + growth: growth - (growth * fees), riskPct: position.initialRiskPct, riskSeries: position.riskSeries, rmultiple: rmultiple, @@ -136,6 +137,11 @@ export function backtest; } + // + // Sum of maker fee and taker fee. + // + const fees = strategy.fees() || 0; + // // Tracks trades that have been closed. // @@ -190,7 +196,7 @@ export function backtest extends I position: IPosition; } +/** + * Computes the fees. + * Return the sum of maker fee and taker fee. + */ +export type FeesFn = () => number; + /** * Arguments to a stop loss rule function. */ @@ -208,4 +214,10 @@ export interface IStrategy; + + /** + * Function that computes the fees + * Return the sum of maker fee and taker fee. + */ + fees: FeesFn; } \ No newline at end of file From 475828a180ae75598f68d0af50cb7346288b19a0 Mon Sep 17 00:00:00 2001 From: Seungwoo321 Date: Mon, 18 Jul 2022 18:05:52 +0900 Subject: [PATCH 2/2] fix: resolve when no fees --- src/lib/backtest.ts | 2 +- src/lib/strategy.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/backtest.ts b/src/lib/backtest.ts index 0a247d9..34ef21b 100644 --- a/src/lib/backtest.ts +++ b/src/lib/backtest.ts @@ -140,7 +140,7 @@ export function backtest