trading-core-lib
Version:
A trading platform core library
219 lines (157 loc) • 5.38 kB
Markdown
# Trading Core Library
A comprehensive TypeScript library for trading platform development with utilities for market data, order management, and financial calculations.
## Features
- **Trading Services**: Order placement, cancellation, and status tracking
- **Market Data**: Real-time and historical market data retrieval
- **Validation**: Comprehensive input validation for trading operations
- **Calculations**: Financial calculations including P&L, percentages, and averages
- **Formatting**: Number and currency formatting utilities
- **TypeScript**: Full TypeScript support with type definitions
## Installation
```bash
npm install trading-core-lib
```
## Usage
### Basic Setup
```typescript
import { TradingService, MarketDataService } from 'trading-core-lib';
// Initialize services
const tradingService = new TradingService({
apiKey: 'your-api-key',
apiSecret: 'your-api-secret',
baseUrl: 'https://api.example.com'
});
const marketDataService = new MarketDataService('https://api.example.com');
```
### Placing Orders
```typescript
import { TradingService } from 'trading-core-lib';
const tradingService = new TradingService();
const order = {
symbol: 'BTC/USD',
side: 'buy',
type: 'market',
quantity: 1
};
const result = await tradingService.placeOrder(order);
if (result.success) {
console.log('Order placed:', result.data);
} else {
console.error('Error:', result.error);
}
```
### Getting Market Data
```typescript
import { MarketDataService } from 'trading-core-lib';
const marketDataService = new MarketDataService();
// Get current market data
const marketData = await marketDataService.getMarketData('BTC/USD');
// Get historical data
const historicalData = await marketDataService.getHistoricalData(
'BTC/USD',
new Date('2023-01-01'),
new Date('2023-01-31')
);
```
### Using Utilities
```typescript
import {
isValidSymbol,
calculateProfitLoss,
formatPrice,
formatCurrency
} from 'trading-core-lib';
// Validation
const isValid = isValidSymbol('BTC/USD'); // true
// Calculations
const profit = calculateProfitLoss(100, 110, 1); // 10
// Formatting
const formattedPrice = formatPrice(12345.6789); // "12345.68"
const formattedCurrency = formatCurrency(1234.56, 'USD'); // "$1,234.56"
```
## API Reference
### TradingService
- `placeOrder(order: Partial<TradeOrder>): Promise<TradingResult>`
- `cancelOrder(orderId: string): Promise<TradingResult>`
- `getOrderStatus(orderId: string): Promise<TradingResult>`
### MarketDataService
- `getMarketData(symbol: string): Promise<TradingResult>`
- `getHistoricalData(symbol: string, startDate: Date, endDate: Date): Promise<TradingResult>`
- `getAvailableSymbols(): Promise<TradingResult>`
### Validation Utils
- `isValidSymbol(symbol: string): boolean`
- `isValidPrice(price: number): boolean`
- `isValidQuantity(quantity: number): boolean`
- `isValidTradeOrder(order: Partial<TradeOrder>): boolean`
### Calculation Utils
- `calculatePercentageChange(oldValue: number, newValue: number): number`
- `calculateTradeValue(price: number, quantity: number): number`
- `calculateProfitLoss(buyPrice: number, sellPrice: number, quantity: number): number`
- `calculateProfitLossPercentage(buyPrice: number, sellPrice: number): number`
- `calculateAveragePrice(trades: Array<{price: number, quantity: number}>): number`
- `roundToDecimals(value: number, decimals: number): number`
### Formatting Utils
- `formatNumber(value: number, decimals?: number): string`
- `formatPrice(price: number): string`
- `formatQuantity(quantity: number): string`
- `formatPercentage(value: number, decimals?: number): string`
- `formatDate(date: Date): string`
- `formatCurrency(amount: number, currency?: string): string`
## Development
### Prerequisites
- Node.js >= 16.0.0
- npm or yarn
### Setup
```bash
# Install dependencies
npm install
# Build the library
npm run build
# Run tests
npm test
# Run linting
npm run lint
# Format code
npm run format
```
## Deployment
### Automatic Deployment (Recommended)
This project uses GitHub Actions for automatic deployment to NPM.
1. **Set up NPM Token**:
- Go to [NPM Settings](https://www.npmjs.com/settings/tokens)
- Create a new access token
- Add it to your GitHub repository secrets as `NPM_TOKEN`
2. **Deploy**:
```bash
# Patch version (1.0.0 → 1.0.1)
npm run version:patch
# Minor version (1.0.0 → 1.1.0)
npm run version:minor
# Major version (1.0.0 → 2.0.0)
npm run version:major
```
### Manual Deployment
```bash
# Build and publish
npm run build
npm publish
```
### Scripts
- `npm run build` - Build the library
- `npm run dev` - Watch mode for development
- `npm test` - Run tests
- `npm run test:watch` - Run tests in watch mode
- `npm run lint` - Run ESLint
- `npm run lint:fix` - Fix ESLint issues
- `npm run format` - Format code with Prettier
- `npm run clean` - Clean build directory
## Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Support
If you have any questions or need help, please open an issue on GitHub.