| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542 |
- #!/usr/bin/env tsx
- /**
- * 流畅式账户注入 API
- * 提供最优雅和直观的账户配置和管理体验
- */
- import { EventEmitter } from 'events'
- // 流畅式账户构建器
- class FluentAccountBuilder {
- private config: any = {}
- static for(exchange: string): FluentAccountBuilder {
- const builder = new FluentAccountBuilder()
- builder.config.exchange = exchange
- return builder
- }
- account(id: string): this {
- this.config.accountId = id
- return this
- }
- alias(name: string): this {
- this.config.alias = name
- return this
- }
- priority(level: number): this {
- this.config.priority = level
- return this
- }
- withTrading(enabled: boolean = true): this {
- this.config.tradingEnabled = enabled
- return this
- }
- withHedging(enabled: boolean = true): this {
- this.config.hedgingEnabled = enabled
- return this
- }
- maxPosition(usd: number): this {
- this.config.maxPositionUsd = usd
- return this
- }
- maxDailyVolume(usd: number): this {
- this.config.maxDailyVolumeUsd = usd
- return this
- }
- withCredentials(creds: Record<string, string>): this {
- this.config.credentials = creds
- return this
- }
- fromEnv(envMapping: Record<string, string>): this {
- this.config.envMapping = envMapping
- return this
- }
- withRisk(limits: { maxDrawdown?: number; maxLosses?: number }): this {
- this.config.riskLimits = limits
- return this
- }
- tagged(...tags: string[]): this {
- this.config.tags = tags
- return this
- }
- build(): any {
- return {
- name: this.config.alias || `${this.config.exchange}-${this.config.accountId}`,
- exchange: this.config.exchange,
- accountId: this.config.accountId || 'default',
- alias: this.config.alias,
- enabled: true,
- priority: this.config.priority || 1,
- tradingEnabled: this.config.tradingEnabled !== false,
- hedgingEnabled: this.config.hedgingEnabled !== false,
- maxPositionUsd: this.config.maxPositionUsd || 1000,
- maxDailyVolumeUsd: this.config.maxDailyVolumeUsd || 10000,
- credentials: this.config.credentials,
- envMapping: this.config.envMapping,
- riskLimits: this.config.riskLimits || {},
- tags: this.config.tags || [],
- }
- }
- }
- // 流畅式账户管理器
- class FluentAccountManager extends EventEmitter {
- private accounts: Map<string, any> = new Map()
- private hedgeGroups: any[] = []
- // 添加单个账户
- add(builderFn: (builder: typeof FluentAccountBuilder) => FluentAccountBuilder): this {
- const account = builderFn(FluentAccountBuilder).build()
- this.accounts.set(account.name, account)
- this.emit('account_added', { account })
- return this
- }
- // 批量添加账户
- addAll(...configs: Array<(builder: typeof FluentAccountBuilder) => FluentAccountBuilder>): this {
- configs.forEach(configFn => this.add(configFn))
- return this
- }
- // 从环境变量自动发现
- discoverFromEnv(): this {
- console.log('🔍 从环境变量自动发现账户...')
- // Pacifica 账户发现
- this.discoverPacificaAccounts()
- // Aster 账户发现
- this.discoverAsterAccounts()
- // Binance 账户发现
- this.discoverBinanceAccounts()
- this.emit('discovery_completed', { count: this.accounts.size })
- return this
- }
- private discoverPacificaAccounts(): void {
- const patterns = [
- // 单账户模式
- { key: 'PACIFICA_PRIVATE_KEY', account: 'PACIFICA_ACCOUNT', suffix: '' },
- // 多账户模式 (1-10)
- ...Array.from({ length: 10 }, (_, i) => ({
- key: `PACIFICA_PRIVATE_KEY_${i + 1}`,
- account: `PACIFICA_ACCOUNT_${i + 1}`,
- suffix: `_${i + 1}`,
- })),
- // 角色模式
- ...['MAIN', 'HEDGE', 'BACKUP', 'TEST'].map(role => ({
- key: `PACIFICA_PRIVATE_KEY_${role}`,
- account: `PACIFICA_ACCOUNT_${role}`,
- suffix: `_${role}`,
- })),
- ]
- patterns.forEach(pattern => {
- if (process.env[pattern.key] && process.env[pattern.account]) {
- const account = FluentAccountBuilder.for('pacifica')
- .account(process.env[pattern.account]!)
- .alias(`Pacifica${pattern.suffix.replace('_', ' ')}`)
- .fromEnv({
- privateKey: pattern.key,
- accountId: pattern.account,
- })
- .tagged('auto-discovered', 'pacifica')
- .build()
- this.accounts.set(account.name, account)
- console.log(` ✅ 发现 Pacifica 账户: ${account.name}`)
- }
- })
- }
- private discoverAsterAccounts(): void {
- const patterns = [
- { user: 'ASTER_ORDER_USER', signer: 'ASTER_ORDER_SIGNER', key: 'PRIVATE_KEY', suffix: '' },
- ...Array.from({ length: 10 }, (_, i) => ({
- user: `ASTER_ORDER_USER_${i + 1}`,
- signer: `ASTER_ORDER_SIGNER_${i + 1}`,
- key: `ASTER_PRIVATE_KEY_${i + 1}`,
- suffix: `_${i + 1}`,
- })),
- ]
- patterns.forEach(pattern => {
- if (process.env[pattern.user] && process.env[pattern.signer] && process.env[pattern.key]) {
- const account = FluentAccountBuilder.for('aster')
- .account(process.env[pattern.user]!)
- .alias(`Aster${pattern.suffix.replace('_', ' ')}`)
- .fromEnv({
- user: pattern.user,
- signer: pattern.signer,
- privateKey: pattern.key,
- })
- .tagged('auto-discovered', 'aster')
- .build()
- this.accounts.set(account.name, account)
- console.log(` ✅ 发现 Aster 账户: ${account.name}`)
- }
- })
- }
- private discoverBinanceAccounts(): void {
- const patterns = [
- { key: 'BINANCE_API_KEY', secret: 'BINANCE_SECRET_KEY', suffix: '' },
- ...Array.from({ length: 10 }, (_, i) => ({
- key: `BINANCE_API_KEY_${i + 1}`,
- secret: `BINANCE_SECRET_KEY_${i + 1}`,
- suffix: `_${i + 1}`,
- })),
- ]
- patterns.forEach(pattern => {
- if (process.env[pattern.key] && process.env[pattern.secret]) {
- const account = FluentAccountBuilder.for('binance')
- .account('default')
- .alias(`Binance${pattern.suffix.replace('_', ' ')}`)
- .fromEnv({
- apiKey: pattern.key,
- apiSecret: pattern.secret,
- })
- .tagged('auto-discovered', 'binance')
- .build()
- this.accounts.set(account.name, account)
- console.log(` ✅ 发现 Binance 账户: ${account.name}`)
- }
- })
- }
- // 创建对冲组
- createHedgeGroup(name: string, strategy: string, ...accountNames: string[]): this {
- const group = {
- name,
- strategy,
- accounts: accountNames,
- enabled: true,
- maxExposureUsd: 50000,
- rebalanceIntervalMs: 30000,
- }
- this.hedgeGroups.push(group)
- this.emit('hedge_group_created', { group })
- return this
- }
- // 启用/禁用账户
- enable(accountName: string): this {
- const account = this.accounts.get(accountName)
- if (account) {
- account.enabled = true
- this.emit('account_enabled', { account })
- }
- return this
- }
- disable(accountName: string): this {
- const account = this.accounts.get(accountName)
- if (account) {
- account.enabled = false
- this.emit('account_disabled', { account })
- }
- return this
- }
- // 获取账户列表
- getAccounts(): any[] {
- return Array.from(this.accounts.values())
- }
- // 按交易所分组
- getByExchange(exchange: string): any[] {
- return this.getAccounts().filter(acc => acc.exchange === exchange)
- }
- // 按标签筛选
- getByTag(tag: string): any[] {
- return this.getAccounts().filter(acc => acc.tags.includes(tag))
- }
- // 获取启用的账户
- getEnabled(): any[] {
- return this.getAccounts().filter(acc => acc.enabled)
- }
- // 生成配置文件
- exportConfig(): any {
- return {
- accounts: this.getAccounts(),
- hedgingGroups: this.hedgeGroups,
- metadata: {
- generatedAt: new Date().toISOString(),
- totalAccounts: this.accounts.size,
- enabledAccounts: this.getEnabled().length,
- },
- }
- }
- // 显示摘要
- summary(): this {
- console.log('\n📊 账户管理摘要')
- console.log('='.repeat(40))
- const accounts = this.getAccounts()
- const enabled = this.getEnabled()
- console.log(`总账户数: ${accounts.length}`)
- console.log(`启用账户: ${enabled.length}`)
- console.log(`对冲组数: ${this.hedgeGroups.length}`)
- // 按交易所统计
- const byExchange = new Map<string, number>()
- accounts.forEach(acc => {
- byExchange.set(acc.exchange, (byExchange.get(acc.exchange) || 0) + 1)
- })
- console.log('\n按交易所分布:')
- byExchange.forEach((count, exchange) => {
- console.log(` ${exchange}: ${count} 个`)
- })
- return this
- }
- // 验证配置
- validate(): { isValid: boolean; errors: string[]; warnings: string[] } {
- const result = { isValid: true, errors: [] as string[], warnings: [] as string[] }
- const accounts = this.getAccounts()
- if (accounts.length === 0) {
- result.errors.push('没有配置任何账户')
- }
- // 检查重复账户ID
- const accountIds = new Set()
- accounts.forEach(acc => {
- const key = `${acc.exchange}:${acc.accountId}`
- if (accountIds.has(key)) {
- result.errors.push(`重复的账户: ${key}`)
- }
- accountIds.add(key)
- })
- // 检查环境变量
- accounts.forEach(acc => {
- if (acc.envMapping) {
- Object.entries(acc.envMapping).forEach(([field, envVar]) => {
- if (!process.env[envVar as string]) {
- result.warnings.push(`${acc.name}: 环境变量 ${envVar} 未设置`)
- }
- })
- }
- })
- result.isValid = result.errors.length === 0
- return result
- }
- }
- // 演示函数
- async function fluentAccountInjectionDemo() {
- console.log('🌟 流畅式账户注入演示')
- console.log('='.repeat(50))
- try {
- // 1. 创建流畅式账户管理器
- console.log('\n🏗️ 创建流畅式账户管理器...')
- const manager = new FluentAccountManager()
- // 设置事件监听
- manager.on('account_added', ({ account }) => {
- console.log(` ➕ 添加账户: ${account.name}`)
- })
- manager.on('discovery_completed', ({ count }) => {
- console.log(` 🔍 自动发现完成: ${count} 个账户`)
- })
- // 2. 手动添加一些优雅配置的账户
- console.log('\n💫 添加精心配置的账户...')
- manager
- .add(builder =>
- builder
- .for('pacifica')
- .account('trading-main')
- .alias('Pacifica 主交易账户')
- .priority(1)
- .withTrading()
- .withHedging()
- .maxPosition(25000)
- .maxDailyVolume(250000)
- .withRisk({ maxDrawdown: 10, maxLosses: 5 })
- .tagged('main', 'high-priority', 'production'),
- )
- .add(builder =>
- builder
- .for('aster')
- .account('hedge-account')
- .alias('Aster 对冲账户')
- .priority(2)
- .withTrading()
- .withHedging()
- .maxPosition(20000)
- .withRisk({ maxDrawdown: 8 })
- .tagged('hedge', 'aster', 'production'),
- )
- .add(builder =>
- builder
- .for('binance')
- .account('backup-spot')
- .alias('Binance 备用现货')
- .priority(3)
- .withTrading(false) // 只读账户
- .withHedging(false)
- .maxPosition(5000)
- .tagged('backup', 'readonly', 'spot'),
- )
- // 3. 自动发现环境变量中的账户
- console.log('\n🔍 自动发现环境变量账户...')
- manager.discoverFromEnv()
- // 4. 创建对冲组
- console.log('\n🔗 创建对冲组...')
- manager
- .createHedgeGroup('main-hedge', 'delta-neutral', 'Pacifica 主交易账户', 'Aster 对冲账户')
- .createHedgeGroup('cross-dex-arbitrage', 'arbitrage', 'Pacifica 主交易账户', 'Binance 备用现货')
- // 5. 显示账户摘要
- manager.summary()
- // 6. 验证配置
- console.log('\n✅ 验证账户配置...')
- const validation = manager.validate()
- if (validation.isValid) {
- console.log('🟢 配置验证通过')
- } else {
- console.log('🔴 配置验证失败:')
- validation.errors.forEach(error => console.log(` ❌ ${error}`))
- }
- if (validation.warnings.length > 0) {
- console.log('⚠️ 警告:')
- validation.warnings.forEach(warning => console.log(` ⚠️ ${warning}`))
- }
- // 7. 展示不同的查询方式
- console.log('\n🔎 智能查询演示...')
- console.log(`📊 启用账户: ${manager.getEnabled().length} 个`)
- console.log(`🏦 Pacifica 账户: ${manager.getByExchange('pacifica').length} 个`)
- console.log(`🏷️ 生产标签账户: ${manager.getByTag('production').length} 个`)
- console.log(`🔄 对冲账户: ${manager.getByTag('hedge').length} 个`)
- // 8. 导出配置
- console.log('\n📄 导出最终配置...')
- const config = manager.exportConfig()
- console.log(`配置已生成:`)
- console.log(` 账户数量: ${config.accounts.length}`)
- console.log(` 对冲组数: ${config.hedgingGroups.length}`)
- console.log(` 生成时间: ${config.metadata.generatedAt}`)
- // 9. 展示配置预览
- if (process.argv.includes('--preview')) {
- console.log('\n📋 配置预览:')
- console.log(JSON.stringify(config, null, 2))
- }
- // 10. 演示动态管理
- console.log('\n🎛️ 动态管理演示...')
- // 禁用备用账户
- manager.disable('Binance 备用现货')
- console.log(' 🔴 已禁用 Binance 备用账户')
- // 启用账户
- manager.enable('Binance 备用现货')
- console.log(' 🟢 已启用 Binance 备用账户')
- console.log('\n✨ 流畅式账户注入演示完成!')
- console.log('\n💡 主要特性:')
- console.log(' 🔹 链式 API 设计,语法简洁直观')
- console.log(' 🔹 智能环境变量发现,支持多种命名约定')
- console.log(' 🔹 类型安全的配置构建')
- console.log(' 🔹 事件驱动的状态管理')
- console.log(' 🔹 灵活的查询和筛选功能')
- console.log(' 🔹 内置验证和风险管理')
- console.log(' 🔹 支持标签和分组管理')
- } catch (error) {
- console.error('❌ 演示失败:', error)
- }
- }
- // 显示 API 使用示例
- function showApiExamples() {
- console.log('\n💡 流畅式 API 使用示例:')
- console.log(`
- // 1. 创建单个账户
- const manager = new FluentAccountManager()
- manager.add(builder => builder
- .for('pacifica')
- .account('my-account')
- .alias('我的 Pacifica 账户')
- .priority(1)
- .withTrading()
- .withHedging()
- .maxPosition(10000)
- .maxDailyVolume(100000)
- .tagged('main', 'production')
- )
- // 2. 批量添加账户
- manager.addAll(
- builder => builder.for('pacifica').account('main').tagged('main'),
- builder => builder.for('aster').account('hedge').tagged('hedge'),
- builder => builder.for('binance').account('spot').withTrading(false)
- )
- // 3. 自动发现 + 手动配置
- manager
- .discoverFromEnv() // 自动发现
- .add(builder => builder.for('pacifica').account('custom')) // 手动添加
- .createHedgeGroup('main-hedge', 'delta-neutral', 'account1', 'account2')
- // 4. 查询和管理
- const pacificaAccounts = manager.getByExchange('pacifica')
- const enabledAccounts = manager.getEnabled()
- const productionAccounts = manager.getByTag('production')
- // 5. 导出配置
- const config = manager.exportConfig()
- `)
- }
- // 运行演示
- if (import.meta.url === `file://${process.argv[1]}`) {
- if (process.argv.includes('--help') || process.argv.includes('-h')) {
- showApiExamples()
- } else {
- fluentAccountInjectionDemo()
- }
- }
|