skayn-trading-sdk
Version:
Professional Bitcoin trading strategy backtesting framework with institutional-grade architecture
214 lines (194 loc) • 6.96 kB
JavaScript
/**
* IExchangeProvider Interface
* Universal interface for all exchange types:
* - Custodial CEX (Binance, LN Markets, Coinbase)
* - Non-custodial DEX (Flashnet, Uniswap, Jupiter)
* - Lightning DEX (Spark-based exchanges)
*
* Enables strategy-agnostic execution across all exchange types
*/
class IExchangeProvider {
constructor(config = {}) {
this.config = config;
this.exchangeType = config.exchangeType || 'unknown'; // 'cex', 'dex', 'lightning'
this.custodyModel = config.custodyModel || 'unknown'; // 'custodial', 'non-custodial'
this.isConnected = false;
}
/**
* Initialize connection to exchange
* @returns {Promise<boolean>} Success status
*/
async connect() {
throw new Error('connect() must be implemented by exchange plugin');
}
/**
* Disconnect from exchange
* @returns {Promise<void>}
*/
async disconnect() {
throw new Error('disconnect() must be implemented by exchange plugin');
}
/**
* Execute trading signal - core method for strategy execution
* @param {Object} signal - Trading signal from strategy
* @param {string} signal.action - 'BUY' or 'SELL'
* @param {number} signal.confidence - Signal confidence (0-1)
* @param {string} signal.strategy - Strategy name
* @param {Object} signal.exitRules - Stop loss, take profit, time stop
* @param {Object} executionParams - Exchange-specific execution parameters
* @returns {Promise<Object>} Execution result
*/
async executeSignal(signal, executionParams = {}) {
throw new Error('executeSignal() must be implemented by exchange plugin');
}
/**
* Place market order
* @param {string} side - 'buy' or 'sell'
* @param {number} amount - Amount in base currency or USD equivalent
* @param {string} symbol - Trading pair (e.g., 'BTCUSDT')
* @param {Object} options - Order options (leverage, stopLoss, takeProfit, etc.)
* @returns {Promise<Object>} Order result
*/
async placeMarketOrder(side, amount, symbol, options = {}) {
throw new Error('placeMarketOrder() must be implemented by exchange plugin');
}
/**
* Place limit order
* @param {string} side - 'buy' or 'sell'
* @param {number} amount - Amount in base currency
* @param {number} price - Limit price
* @param {string} symbol - Trading pair
* @param {Object} options - Order options
* @returns {Promise<Object>} Order result
*/
async placeLimitOrder(side, amount, price, symbol, options = {}) {
throw new Error('placeLimitOrder() must be implemented by exchange plugin');
}
/**
* Cancel order
* @param {string} orderId - Order ID to cancel
* @param {string} symbol - Trading pair
* @returns {Promise<Object>} Cancellation result
*/
async cancelOrder(orderId, symbol) {
throw new Error('cancelOrder() must be implemented by exchange plugin');
}
/**
* Get current positions
* @param {string} symbol - Optional symbol filter
* @returns {Promise<Array>} Array of position objects
*/
async getPositions(symbol = null) {
throw new Error('getPositions() must be implemented by exchange plugin');
}
/**
* Get account balance
* @param {string} asset - Optional asset filter (e.g., 'BTC', 'USDT')
* @returns {Promise<Object>} Balance information
*/
async getBalance(asset = null) {
throw new Error('getBalance() must be implemented by exchange plugin');
}
/**
* Get order history
* @param {string} symbol - Trading pair
* @param {number} limit - Maximum number of orders to return
* @returns {Promise<Array>} Array of historical orders
*/
async getOrderHistory(symbol, limit = 100) {
throw new Error('getOrderHistory() must be implemented by exchange plugin');
}
/**
* Get current market price
* @param {string} symbol - Trading pair
* @returns {Promise<number>} Current market price
*/
async getCurrentPrice(symbol) {
throw new Error('getCurrentPrice() must be implemented by exchange plugin');
}
/**
* Check if exchange supports specific features
* @param {string} feature - Feature to check ('leverage', 'stopLoss', 'takeProfit', 'futures', etc.)
* @returns {boolean} Whether feature is supported
*/
supportsFeature(feature) {
throw new Error('supportsFeature() must be implemented by exchange plugin');
}
/**
* Get exchange-specific configuration requirements
* @returns {Object} Configuration schema and requirements
*/
getConfigRequirements() {
throw new Error('getConfigRequirements() must be implemented by exchange plugin');
}
/**
* Validate configuration before connection
* @param {Object} config - Configuration to validate
* @returns {Object} Validation result with issues array
*/
validateConfig(config) {
throw new Error('validateConfig() must be implemented by exchange plugin');
}
/**
* Get exchange status and health
* @returns {Promise<Object>} Exchange status information
*/
async getExchangeStatus() {
return {
name: this.constructor.name,
exchangeType: this.exchangeType,
custodyModel: this.custodyModel,
isConnected: this.isConnected,
supportsFeatures: this.getSupportedFeatures(),
lastUpdated: new Date().toISOString()
};
}
/**
* Get list of supported features for this exchange
* @returns {Array} Array of supported feature strings
*/
getSupportedFeatures() {
throw new Error('getSupportedFeatures() must be implemented by exchange plugin');
}
/**
* Handle exchange-specific error mapping
* @param {Error} error - Raw exchange error
* @returns {Object} Standardized error object
*/
mapError(error) {
return {
type: 'exchange_error',
exchange: this.constructor.name,
originalError: error.message,
code: error.code || 'unknown',
timestamp: new Date().toISOString(),
retryable: false
};
}
/**
* Calculate position size based on strategy signal and exchange capabilities
* @param {Object} signal - Trading signal
* @param {number} portfolioValue - Current portfolio value
* @param {number} currentPrice - Current asset price
* @returns {Object} Position sizing information
*/
calculatePositionSize(signal, portfolioValue, currentPrice) {
throw new Error('calculatePositionSize() must be implemented by exchange plugin');
}
/**
* Set up risk management parameters for this exchange
* @param {Object} riskParams - Risk management parameters
* @returns {Promise<void>}
*/
async setupRiskManagement(riskParams) {
throw new Error('setupRiskManagement() must be implemented by exchange plugin');
}
/**
* Emergency stop - close all positions and cancel all orders
* @returns {Promise<Object>} Emergency stop result
*/
async emergencyStop() {
throw new Error('emergencyStop() must be implemented by exchange plugin');
}
}
module.exports = IExchangeProvider;