Skip to content

Commit e4c4a72

Browse files
committed
next migrations iteration
1 parent 0ad59d2 commit e4c4a72

30 files changed

+275
-172
lines changed

TYPESCRIPT_MIGRATION.md

Lines changed: 55 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# TypeScript Migration Progress
22

33
**Date**: 2025-02-10
4-
**Branch**: `feature/ejs-templates`
4+
**Branch**: `feature/typescript-step-migration`
55
**Goal**: Migrate `src/` directory from JavaScript to TypeScript
66

77
## Setup Complete
@@ -97,14 +97,20 @@ telegram.ts (uses TelegramConfig interface, Telegraf)
9797
tickers.ts
9898
```
9999

100-
### src/utils/ (9 files with tests - 100%)
100+
### src/utils/ (15 files - 100%)
101101
```
102102
order_util.ts (+ test)
103103
resample.ts (+ test)
104104
technical_pattern.ts (+ test)
105105
technical_analysis.ts (+ test)
106106
technical_analysis_validator.ts (+ test)
107-
request_client.ts (+ test) - uses Logger interface
107+
request_client.ts (+ test)
108+
common_util.ts ✅ NEW
109+
indicators.ts ✅ NEW
110+
instance_util.ts ✅ NEW
111+
queue.ts ✅ NEW
112+
throttler.ts ✅ NEW
113+
winston_sqlite_transport.ts ✅ NEW
108114
```
109115

110116
### src/modules/system/ (1 file - 100%)
@@ -118,19 +124,17 @@ index.ts (migrated from index.js)
118124
```
119125

120126
### Test Status
121-
-28 tests passing
127+
-140 tests passing
122128
- All migrated tests use TypeScript
123129

124130
## 📋 Remaining Files to Migrate
125131

126-
### src/utils/ (6 files without tests)
132+
### src/exchange/utils/** (4 files - 100%)
127133
```
128-
common_util.js
129-
indicators.js
130-
instance_util.js
131-
queue.js
132-
throttler.js
133-
winston_sqlite_transport.js
134+
ccxt_util.ts ✅
135+
order_bag.ts ✅ (+ test)
136+
trades_util.ts ✅ (+ test)
137+
candles_from_trades.ts ✅
134138
```
135139

136140
### src/exchange/ (13+ files, some with tests)
@@ -146,10 +150,6 @@ bybit.js (+ test)
146150
bybit_unified.js
147151
coinbase_pro.js (+ test)
148152
noop.js
149-
utils/ccxt_util.js
150-
utils/order_bag.js (+ test)
151-
utils/trades_util.js (+ test)
152-
utils/candles_from_trades.js
153153
ccxt/ccxt_exchange_order.js
154154
```
155155

@@ -158,43 +158,41 @@ ccxt/ccxt_exchange_order.js
158158
backfill.js
159159
backtest.js
160160
exchange/
161-
exchange_manager.ts (+ test)
162-
exchange_candle_combine.ts (+ test)
161+
exchange_manager.ts (+ test) ✅ import fixed
162+
exchange_candle_combine.ts (+ test) ✅ import fixed
163163
exchange_position_watcher.ts (+ test)
164164
listener/
165-
listener/create_order_listener.js (fixed import)
166-
listener/tick_listener.js (+ test)
167-
listener/create_order_listener.js (+ test)
168-
listener/exchange_order_watchdog_listener.js (+ test)
165+
listener/tick_listener.js (+ test) ✅ import fixed
166+
listener/create_order_listener.js (+ test) ✅ import fixed
167+
listener/exchange_order_watchdog_listener.js (+ test) ✅ import fixed
169168
order/
170-
order_executor.ts (+ test)
169+
order_executor.ts (+ test) ✅ import fixed
171170
order_calculator.ts (+ test)
172171
stop_loss_calculator.ts (+ test)
173-
risk_reward_ratio_calculator.ts (+ test)
172+
risk_reward_ratio_calculator.ts (+ test) ✅ import fixed
174173
orders/
175-
orders_http.ts
174+
orders_http.ts ✅ import fixed
176175
pairs/
177176
pairs_http.ts
178-
pair_config.js
177+
pair_config.js ✅ import fixed
179178
pair_interval.js
180-
pair_state_manager.ts (+ test)
181-
pair_state_execution.ts (+ test)
179+
pair_state_manager.ts (+ test) ✅ import fixed
180+
pair_state_execution.ts (+ test) ✅ import fixed
182181
repository/
183182
signal/
184183
signal_http.ts
185184
signal_logger.ts
186185
strategy/
187-
strategy_manager.ts (+ test)
186+
strategy_manager.ts (+ test) ✅ import fixed
188187
strategies/
189188
dict/
190189
system/
191-
system_util.ts ✅
192190
logs_http.ts
193191
candle_importer.js
194192
candle_export_http.js
195-
candlestick_resample.js
193+
candlestick_resample.js ✅ import fixed
196194
services.js
197-
ta.js
195+
ta.js ✅ import fixed
198196
trade.js
199197
```
200198

@@ -224,30 +222,6 @@ export type PairStateType = 'long' | 'short' | 'close' | 'cancel';
224222
export type ClearCallback = () => void;
225223
```
226224

227-
### Utility Types (src/utils/)
228-
```typescript
229-
// Resample
230-
export interface Candlestick {
231-
time: number;
232-
open: number;
233-
high: number;
234-
low: number;
235-
close: number;
236-
volume: number;
237-
}
238-
239-
// Request Client
240-
export interface Logger {
241-
error(message: string): void;
242-
}
243-
244-
// Technical Analysis
245-
export interface IndicatorResult {
246-
[key: string]: any;
247-
candles: Candlestick[];
248-
}
249-
```
250-
251225
## 🚀 How to Continue
252226

253227
### For utils without tests:
@@ -261,7 +235,7 @@ export interface IndicatorResult {
261235
2. Create TS file for source
262236
3. Create TS file for test
263237
4. Delete both JS files
264-
5. Run specific test: `npx mocha --require ts-node_register "test/path/to.test.ts"`
238+
5. Run specific test: `npx mocha --require ts-node/register "test/path/to.test.ts"`
265239

266240
### For complex dependencies:
267241
1. Start with leaf dependencies (no imports of other non-TS files)
@@ -273,30 +247,33 @@ export interface IndicatorResult {
273247
### Import Statement Changes
274248
- Changed `require('../../dict/candlestick.js')` to `require('../../dict/candlestick')` (no .js extension)
275249
- This allows Node.js/ts-node to find .ts files
276-
277-
### External Dependencies
278-
Currently using `any` for:
279-
- Mailer (nodemailer)
280-
- SystemUtil (before migration - now has Config interface)
281-
- Logger (winston)
282-
- Telegraf
283-
- Request library
284-
285-
These can be typed more strictly later if needed.
250+
- **When importing TS files with named exports from JS, use destructuring:**
251+
```javascript
252+
const { RequestClient } = require('../utils/request_client');
253+
```
286254

287255
### allowJs: true
288256
The `allowJs: true` flag in tsconfig.json allows mixed JS/TS during migration.
289-
This means you can migrate file-by-file without breaking everything.
257+
258+
### Backwards Compatibility Exports
259+
When migrating utility modules that were originally exporting objects, maintain backwards compatibility by exporting both named functions and a convenience object:
260+
```typescript
261+
// Named exports for TS imports
262+
export function isPercentDifferentGreaterThen(...) { ... }
263+
264+
// Object export for JS imports expecting the old pattern
265+
export const orderUtil = { isPercentDifferentGreaterThen };
266+
export const OrderUtil = orderUtil; // also capitalize for consistency
267+
```
268+
269+
This allows both TS imports (`import { isPercentDifferentGreaterThen }`) and JS imports (`const { OrderUtil } = require(...)`) to work.
290270

291271
## ✅ Verification Commands
292272

293273
```bash
294274
# Run all TypeScript tests
295275
npm test
296276

297-
# Run specific test
298-
npx mocha --require ts-node/register "test/utils/order_util.test.ts"
299-
300277
# Start server
301278
npm start
302279

@@ -306,16 +283,14 @@ npm run build
306283

307284
## 🎯 Next Steps Priority
308285

309-
1. **Finish src/utils/** (6 remaining files) - Quick wins, small files
310-
2. **src/exchange/utils/** - Has tests, good candidates
311-
3. **src/exchange/*.js** - Exchange implementations, some with tests
312-
4. **src/modules/strategy/** - Core trading logic, has tests
313-
5. **src/modules/listener/** - Event listeners, has tests
314-
6. **src/modules/** - Remaining modules
286+
1. **src/exchange/utils/** - Has tests, good candidates** ✅ DONE
287+
2. **src/exchange/*.js** - Exchange implementations, some with tests** ← CURRENT
288+
3. **src/modules/strategy/** - Core trading logic, has tests
289+
4. **src/modules/** - Remaining modules
315290

316291
## 📊 Progress Stats
317292

318-
- **~50 files migrated**
319-
- **28 tests passing**
320-
- **~100+ files remaining**
321-
- **~30% complete** (estimated)
293+
- **~70 files migrated**
294+
- **140 tests passing**
295+
- **~80 files remaining**
296+
- **~47% complete** (estimated)

src/exchange/binance.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ const { ExchangeOrder } = require('../dict/exchange_order');
99
const { OrderUtil } = require('../utils/order_util');
1010
const { Position } = require('../dict/position');
1111
const { Order } = require('../dict/order');
12-
const OrderBag = require('./utils/order_bag');
13-
const TradesUtil = require('./utils/trades_util');
12+
const { OrderBag } = require('./utils/order_bag');
13+
const { TradesUtil } = require('./utils/trades_util');
1414

1515
module.exports = class Binance {
1616
constructor(eventEmitter, logger, queue, candleImport, throttler) {

src/exchange/binance_margin.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ const { Ticker } = require('../dict/ticker');
1010
const { TickerEvent } = require('../event/ticker_event');
1111
const { ExchangeOrder } = require('../dict/exchange_order');
1212
const { OrderUtil } = require('../utils/order_util');
13-
const TradesUtil = require('./utils/trades_util');
13+
const { TradesUtil } = require('./utils/trades_util');
1414
const { Position } = require('../dict/position');
1515
const { Order } = require('../dict/order');
16-
const OrderBag = require('./utils/order_bag');
16+
const { OrderBag } = require('./utils/order_bag');
1717

1818
module.exports = class BinanceMargin {
1919
constructor(eventEmitter, logger, queue, candleImport, throttler) {

src/exchange/bybit_unified.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ const { ExchangeCandlestick } = require('../dict/exchange_candlestick');
66
const { Position } = require('../dict/position');
77
const CommonUtil = require('../utils/common_util');
88
const { ExchangeOrder } = require('../dict/exchange_order');
9-
const OrderBag = require('./utils/order_bag');
9+
const { OrderBag } = require('./utils/order_bag');
1010
const { Order } = require('../dict/order');
1111
const { orderUtil } = require('../utils/order_util');
1212

src/exchange/ccxt/ccxt_exchange_order.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
const ccxt = require('ccxt');
22
const _ = require('lodash');
3-
const OrderBag = require('../utils/order_bag');
3+
const { OrderBag } = require('../utils/order_bag');
44
const Order = require('../../dict/order');
55
const ExchangeOrder = require('../../dict/exchange_order');
6-
const CcxtUtil = require('../utils/ccxt_util');
6+
const { CcxtUtil } = require('../utils/ccxt_util');
77

88
module.exports = class CcxtExchangeOrder {
99
constructor(ccxtClient, symbols, logger, callbacks) {
Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,50 @@
1-
const ExchangeCandlestick = require('../../dict/exchange_candlestick');
2-
3-
module.exports = class CandlesFromTrades {
4-
constructor(candlestickResample, candleImporter) {
1+
import { ExchangeCandlestick } from '../../dict/exchange_candlestick';
2+
3+
export interface Trade {
4+
price: number;
5+
amount: number;
6+
symbol: string;
7+
timestamp: number;
8+
}
9+
10+
export interface SymbolConfig {
11+
symbol: string;
12+
periods: string[];
13+
}
14+
15+
export interface CandlestickResample {
16+
resample(exchange: string, symbol: string, periodFrom: string, periodTo: string, limitCandles: boolean): Promise<void>;
17+
}
18+
19+
export interface CandleImporter {
20+
insertThrottledCandles(candles: ExchangeCandlestick[]): Promise<void>;
21+
}
22+
23+
interface InternalCandle {
24+
timestamp: number;
25+
open: number;
26+
high: number;
27+
low: number;
28+
close: number;
29+
volume: number;
30+
closed: boolean;
31+
}
32+
33+
export class CandlesFromTrades {
34+
private candlestickResample: CandlestickResample;
35+
private candleImporter: CandleImporter;
36+
private candles: Record<string, Record<number, InternalCandle>>;
37+
private lastCandleMap: Record<string, InternalCandle>;
38+
39+
constructor(candlestickResample: CandlestickResample, candleImporter: CandleImporter) {
540
this.candlestickResample = candlestickResample;
641
this.candleImporter = candleImporter;
742

843
this.candles = {};
944
this.lastCandleMap = {};
1045
}
1146

12-
async onTrades(exchangeName, trades, symbols = []) {
47+
async onTrades(exchangeName: string, trades: Trade[], symbols: SymbolConfig[] = []): Promise<void> {
1348
for (const trade of trades) {
1449
await this.onTrade(exchangeName, trade, symbols);
1550
}
@@ -22,14 +57,14 @@ module.exports = class CandlesFromTrades {
2257
* @param trade array
2358
* @param symbols array for calculate the resamples
2459
*/
25-
async onTrade(exchangeName, trade, symbols = []) {
60+
async onTrade(exchangeName: string, trade: Trade, symbols: SymbolConfig[] = []): Promise<void> {
2661
if (!trade.price || !trade.amount || !trade.symbol || !trade.timestamp) {
2762
return;
2863
}
2964

3065
// Price and volume are sent as strings by the API
31-
trade.price = parseFloat(trade.price);
32-
trade.amount = parseFloat(trade.amount);
66+
trade.price = parseFloat(trade.price.toString());
67+
trade.amount = parseFloat(trade.amount.toString());
3368

3469
const { symbol } = trade;
3570

@@ -75,7 +110,7 @@ module.exports = class CandlesFromTrades {
75110
closed: false
76111
};
77112

78-
const ourCandles = [];
113+
const ourCandles: ExchangeCandlestick[] = [];
79114
for (const timestamp in this.candles[symbol]) {
80115
const candle = this.candles[symbol][timestamp];
81116

@@ -96,7 +131,7 @@ module.exports = class CandlesFromTrades {
96131

97132
// delete old candles
98133
Object.keys(this.candles[symbol])
99-
.sort((a, b) => b - a)
134+
.sort((a, b) => Number(b) - Number(a))
100135
.slice(200)
101136
.forEach(i => {
102137
delete this.candles[symbol][i];
@@ -118,4 +153,4 @@ module.exports = class CandlesFromTrades {
118153
})
119154
);
120155
}
121-
};
156+
}

0 commit comments

Comments
 (0)