skayn-trading-sdk
Version:
Professional Bitcoin trading strategy backtesting framework with institutional-grade architecture
113 lines (97 loc) ⢠4.7 kB
JavaScript
const { SDK } = require('../index');
const SmartDataProvider = require('./smart-data-provider');
// Helper function for moving averages
function average(arr) {
return arr.reduce((sum, val) => sum + val, 0) / arr.length;
}
// Smart data provider - tries real data, falls back to synthetic
const smartDataProvider = new SmartDataProvider();
// Simple moving average crossover strategy
const movingAverageStrategy = SDK.strategy(async (data, portfolio) => {
if (data.length < 50) {
return { action: 'HOLD', confidence: 0, strategy: 'conservative', reasons: ['Not enough data'] };
}
const prices = data.map(bar => bar.close);
const sma20 = average(prices.slice(-20));
const sma50 = average(prices.slice(-50));
const currentPrice = prices[prices.length - 1];
console.log(`Current Price: $${currentPrice.toFixed(0)}, SMA20: $${sma20.toFixed(0)}, SMA50: $${sma50.toFixed(0)}`);
// Calculate confidence based on spread and strength
const spread = Math.abs(sma20 - sma50) / sma50;
const confidence = Math.min(spread * 50, 0.95); // Max 95% confidence
if (sma20 > sma50 * 1.002 && confidence > 0.35) { // 0.2% threshold + 35% confidence - more active for beta demo
return {
action: 'BUY',
confidence: confidence,
quantity: 0.001, // 0.001 BTC
strategy: 'conservative',
reasons: [`Conservative BUY: SMA20 (${sma20.toFixed(0)}) > SMA50 (${sma50.toFixed(0)}) with ${(confidence*100).toFixed(1)}% confidence`]
};
} else if (sma20 < sma50 * 0.998 && confidence > 0.35) { // 0.2% threshold + 35% confidence
return {
action: 'SELL',
confidence: confidence,
quantity: 0.001,
strategy: 'conservative',
reasons: [`Conservative SELL: SMA20 (${sma20.toFixed(0)}) < SMA50 (${sma50.toFixed(0)}) with ${(confidence*100).toFixed(1)}% confidence`]
};
}
return { action: 'HOLD', confidence: confidence, strategy: 'conservative', reasons: [`Below 35% confidence: ${(confidence*100).toFixed(1)}%`] };
}, {
name: 'Swing Moving Average Strategy',
description: 'High-confidence SMA20/SMA50 crossover for swing trading (85% threshold)',
version: '2.0.0',
stopLoss: '5%',
profitTarget: '7%',
maxHoldTime: '72 hours'
});
// Run the backtest
async function runExample() {
console.log('šÆ Running Skayn SDK Example - Moving Average Strategy\n');
try {
const results = await SDK.create()
.strategy(movingAverageStrategy)
.dataProvider(smartDataProvider)
.backtest({
startDate: '2024-01-01',
endDate: '2024-01-31',
initialBalance: 8860000, // 8.86M sats (~$10,000 at $112,900/BTC)
symbol: 'BTCUSDT'
});
console.log('\nš Backtest Results:');
console.log('ā'.repeat(50));
console.log('ā ļø DISCLAIMER: Past performance does not guarantee future results.');
console.log(' This is a demonstration using historical data for educational purposes only.\n');
console.log(`Initial Balance: ${results.initialBalance?.toLocaleString() || 'N/A'} sats`);
console.log(`Final Balance: ${results.finalBalance?.toLocaleString() || 'N/A'} sats`);
console.log(`Total Return: ${results.totalReturn?.toFixed(2) || 'N/A'}%`);
console.log(`Number of Trades: ${results.totalTrades || 'N/A'}`);
console.log(`Win Rate: ${results.winRate?.toFixed(1) || 'N/A'}%`);
console.log(`Max Drawdown: ${results.maxDrawdown?.toFixed(2) || 'N/A'}%`);
if (results.trades && results.trades.length > 0) {
console.log('\nš Recent Trades:');
results.trades.slice(-3).forEach((trade, i) => {
const action = trade.signal?.action || 'N/A';
const price = trade.position?.entryPrice || trade.closedPosition?.entryPrice;
const pnl = trade.realizedPnL || trade.closedPosition?.realizedPnL;
console.log(`${i + 1}. ${action} at $${price?.toFixed(0) || 'N/A'} - P&L: ${pnl?.toFixed(0) || 'N/A'} sats`);
});
}
} catch (error) {
console.error('ā Error running backtest:', error.message);
}
}
// Run the example if this file is executed directly
if (require.main === module) {
console.log('šļø Skayn Trading SDK Structure:');
console.log(' š /src - Core trading framework');
console.log(' š /examples - Demo strategies (this file)');
console.log(' š /tests - Test suites');
console.log('');
console.log('Look at this structure - /src/backtesting, /src/interfaces, /src/core.');
console.log('This is how professional trading firms organize their systems.');
console.log('We\'ve just made it accessible to everyone.\n');
runExample();
}
module.exports = { runExample };