Skip to content

WIP: univ3 lp backtest #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,274 changes: 1,274 additions & 0 deletions src/backtests/univ3/lpSim/grafana.json

Large diffs are not rendered by default.

31 changes: 31 additions & 0 deletions src/backtests/univ3/lpSim/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Backtest } from '../../../lib/backtest.js';
import { DataSourceInfo } from '../../../lib/datasource/types.js';
import { HedgedUniswapStrategyRunner } from './strategyRunner.js';

const main = async () => {
const USDCWETH = '0xb1026b8e7276e7ac75410f1fcbbe21796e8f7526';
const sources: DataSourceInfo[] = [
{
chain: 'arbitrum',
protocol: 'camelot-dex',
resoution: '1h',
config: {
pairs: [USDCWETH],
},
},
];
const start = new Date('2023-06-20');
const end = new Date();
const bt = await Backtest.create(start, end, sources);

// Configure Strategy
const strategy = new HedgedUniswapStrategyRunner(end);
bt.onBefore(strategy.before.bind(strategy));
bt.onData(strategy.onData.bind(strategy));
bt.onAfter(strategy.after.bind(strategy));

// Run
await bt.run();
};

main();
12 changes: 12 additions & 0 deletions src/backtests/univ3/lpSim/models.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ILogAny } from '../../../lib/utils/influx2x.js';
import { InfluxBatcher } from '../../../lib/utils/influxBatcher.js';

export const Log = new InfluxBatcher<ILogAny, any, any>(
'hedged_camelot3_strategy',
);
export const Rebalance = new InfluxBatcher<ILogAny, any, any>(
'hedged_camelot3_rebalance',
);
export const Summary = new InfluxBatcher<ILogAny, any, any>(
'hedged_camelot3_summary',
);
23 changes: 23 additions & 0 deletions src/backtests/univ3/lpSim/stats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export class Stats {
// Calculate the average of all the numbers
static mean(values: number[]) {
const mean = values.reduce((sum, current) => sum + current) / values.length;
return mean;
}

// Calculate variance
static variance(values: number[]) {
const average = Stats.mean(values);
const squareDiffs = values.map((value) => {
const diff = value - average;
return diff * diff;
});
const variance = Stats.mean(squareDiffs);
return variance;
}

// Calculate stand deviation
static stddev(variance: number) {
return Math.sqrt(variance);
}
}
108 changes: 108 additions & 0 deletions src/backtests/univ3/lpSim/strategyRunner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { UniV3PositionManager } from '../../../lib/protocols/UNIV3PositionManager.js';
import { Uni3Snaphot } from '../../../lib/datasource/univ3Dex.js';
import { stringify } from 'csv-stringify/sync';
import fs from 'fs/promises';
import { UniV3Hodl } from './univ3Hodl.js';
import { Log, Rebalance, Summary } from './models.js';
import { range } from '../../../lib/utils/utility.js';
import { permutations } from '../../../lib/utils/permutations.js';

const SECONDS_IN_DAY = 60 * 60 * 24;
const MILLISECONDS_IN_DAY = SECONDS_IN_DAY * 1000;
const PERIOD = 8 * 7; // 8 weeks

const POOLS = ['Camelotv3 WETH/USDC 0%'];

export class HedgedUniswapStrategyRunner {
private uni = new UniV3PositionManager();
private lastData!: Uni3Snaphot;
private lastStart?: number;
private strategies: UniV3Hodl[] = [];

constructor(private end: Date) {}

public async startNewStartForPool(pool: string) {
const rangeSpread = range(0.05, 0.25, 5);
const fixedSlippage = range(0.004, 0.01, 1);

const variations = permutations([rangeSpread, fixedSlippage]);

variations.forEach((e) => {
this.strategies.push(
new UniV3Hodl({
name: `#${e[0]}: Camelotv3 WETH/USDC ${e[0] * 100}% | slippage : ${
e[1] * 100
}%`,
poolSymbol: pool,
initial: 10_000,
rangeSpread: e[0],
priceToken: 0,
fixedSlippage: e[1],
period: PERIOD,
}),
);
});
}

public async before() {
await Log.dropMeasurement();
}

public async after() {
console.log(
'end date:',
new Date(this.lastData.timestamp * 1000).toISOString(),
);
await Log.exec(true);
await Rebalance.exec(true);
const summary = this.strategies.map((s) => s.summary);
console.log(summary);
const csv = stringify(summary, { header: true });
fs.writeFile('./camelotv3_hedged.csv', csv);

const series = this.strategies.map((s) => s.series).flat();
const seriesCsv = stringify(series, { header: true });
fs.writeFile('./camelotv3_hedged_series.csv', seriesCsv);

await Summary.writePoints(
summary.map((s, i) => {
return {
tags: this.strategies[i].tags,
fields: s,
timestamp: new Date(this.lastData.timestamp * 1000),
};
}),
);
await Summary.exec();
}

public async onData(snapshot: Uni3Snaphot) {
if (!snapshot.data.univ3) return console.log('missing data', snapshot);
this.lastData = snapshot;

this.uni.processPoolData(snapshot);

const daysElapsed = Math.floor(
(snapshot.timestamp - this.lastStart!) / SECONDS_IN_DAY,
);
const daysRemaining =
(this.end.getTime() - snapshot.timestamp * 1000) / MILLISECONDS_IN_DAY;

// Create new strategies every 3 days
if (
(this.strategies.length === 0 || daysElapsed > 3) &&
daysRemaining > PERIOD
) {
for (const pool of POOLS) {
console.log('start strat', pool, new Date(snapshot.timestamp * 1000));
this.startNewStartForPool(pool);
}
this.lastStart = snapshot.timestamp;
}

// Process the strategy
for (const strat of this.strategies) {
await strat.process(this.uni, snapshot);
}
}
}
Loading