Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wip: typescript migration #127

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions index.js → index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ program
.command('trade')
.description('start crypto trading bot')
.option('-i, --instance <file>', 'Instance to start', 'instance.json')
.action(async options => {
.action(async (options: any) => {
await services.boot(__dirname);

const cmd = new TradeCommand(options.instance);
Expand All @@ -24,7 +24,7 @@ program
.option('-s, --symbol <symbol>')
.option('-p, --period <period>', '1m 5m, 15m, 1h', '15m')
.option('-d, --date <date>', 'days in past to collect start', '7')
.action(async options => {
.action(async (options: any) => {
if (!options.exchange || !options.symbol || !options.period || !options.date) {
throw new Error('Not all options are given');
}
Expand All @@ -41,7 +41,7 @@ program
.command('server')
.description('')
.option('-i, --instance <file>', 'Instance to start', 'instance.json')
.action(options => {
.action((options: any) => {
const cmd = new ServerCommand(options.instance);
cmd.execute();
});
Expand Down
53 changes: 29 additions & 24 deletions src/exchange/bitfinex.js → src/exchange/bitfinex.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const BFX = require('bitfinex-api-node');

const { Order } = require('bfx-api-node-models');
const moment = require('moment');
const _ = require('lodash');
import moment from 'moment';
import _ = require('lodash');
const ExchangeCandlestick = require('./../dict/exchange_candlestick');
const Ticker = require('./../dict/ticker');
const Position = require('../dict/position');
Expand All @@ -12,19 +12,29 @@ const ExchangeOrder = require('../dict/exchange_order');
const OrderUtil = require('../utils/order_util');

module.exports = class Bitfinex {
eventEmitter: any;
candleImport: any;
logger: any;
positions: {};
requestClient: any;
exchangePairs: {};
tickers: {};
client: any;
orders: any;

constructor(eventEmitter, logger, requestClient, candleImport) {
this.eventEmitter = eventEmitter;
this.candleImport = candleImport;
this.logger = logger;
this.positions = {};
this.orders = [];
this.orders = {};
this.requestClient = requestClient;
this.exchangePairs = {};
this.tickers = {};
}

start(config, symbols) {
const subscriptions = [];
const subscriptions: any[] = [];

symbols.forEach(instance => {
// candles
Expand Down Expand Up @@ -111,7 +121,7 @@ module.exports = class Bitfinex {
return;
}

const order = Bitfinex.createExchangeOrder(orderUpdate);
const order = Bitfinex.createExchangeOrder({ order: orderUpdate });

this.logger.info(`Bitfinex: order update: ${JSON.stringify(order)}`);
this.orders[order.id] = order;
Expand All @@ -120,20 +130,20 @@ module.exports = class Bitfinex {
async order(order) {
const result = await new Order(Bitfinex.createOrder(order)).submit(this.client);

const executedOrder = Bitfinex.createExchangeOrder(result);
const executedOrder = Bitfinex.createExchangeOrder({ order: result });
this.triggerOrder(executedOrder);

return executedOrder;
}

async updateOrder(id, order) {
const changes = {
const changes: { id: any, amount?: string, price?: string } = {
id: id
};

if (order.getAmount()) {
// amount need be negative on sell / short orders; as on order create
const ourOrder = await this.findOrderById(id);
const ourOrder: any = await this.findOrderById(id);
changes.amount = String(ourOrder && ourOrder.isShort() ? order.getAmount() * -1 : order.getAmount());
}

Expand All @@ -151,14 +161,14 @@ module.exports = class Bitfinex {

const unseralized = Order.unserialize(result);

const executedOrder = Bitfinex.createExchangeOrder(unseralized);
const executedOrder = Bitfinex.createExchangeOrder({ order: unseralized });
this.triggerOrder(executedOrder);

return executedOrder;
}

async getOrders() {
const orders = [];
const orders: any[] = [];

for (const key in this.orders) {
if (this.orders[key].status === 'open') {
Expand All @@ -170,7 +180,7 @@ module.exports = class Bitfinex {
}

async getOrdersForSymbol(symbol) {
const orders = [];
const orders: any[] = [];

for (const key in this.orders) {
const order = this.orders[key];
Expand Down Expand Up @@ -216,7 +226,7 @@ module.exports = class Bitfinex {
}

async getPositions() {
const positions = [];
const positions: any[] = [];

for (const symbol in this.positions) {
let position = this.positions[symbol];
Expand Down Expand Up @@ -268,9 +278,8 @@ module.exports = class Bitfinex {
id = parseInt(id);
}

let result;
try {
result = await this.client.cancelOrder(id);
await this.client.cancelOrder(id);
} catch (e) {
this.logger.error(`Bitfinex: cancel order error: ${e}`);
return undefined;
Expand All @@ -286,7 +295,7 @@ module.exports = class Bitfinex {
}

async cancelAll(symbol) {
const orders = [];
const orders: any[] = [];

for (const order of await this.getOrdersForSymbol(symbol)) {
orders.push(await this.cancelOrder(order.id));
Expand Down Expand Up @@ -361,7 +370,7 @@ module.exports = class Bitfinex {
this.orders[order.id] = order;
}

static createExchangeOrder(order) {
static createExchangeOrder(order: any) {
let status;
let retry = false;

Expand All @@ -378,11 +387,7 @@ module.exports = class Bitfinex {
}

const bitfinex_id = order.id;
const created_at = order.status;
// let filled_size = n(position[7]).subtract(ws_order[6]).format('0.00000000')
const bitfinex_status = order.status;
const { price } = order;
const { price_avg } = order;

let orderType;
switch (order.type.toLowerCase().replace(/[\W_]+/g, '')) {
Expand Down Expand Up @@ -436,7 +441,7 @@ module.exports = class Bitfinex {
static createOrder(order) {
const amount = order.getAmount();

const orderOptions = {
const orderOptions: { symbol: string; amount: any; meta: { aff_code: string }; cid: any, price?: string, type?: any } = {
cid: order.getId(),
symbol: `t${order.getSymbol()}`,
amount: order.isShort() ? amount * -1 : amount,
Expand Down Expand Up @@ -564,7 +569,7 @@ module.exports = class Bitfinex {
mySymbol = mySymbol.substring(1);
}

const myCandles = [];
const myCandles: any[] = [];

if (Array.isArray(candles)) {
candles.forEach(function(candle) {
Expand All @@ -575,10 +580,10 @@ module.exports = class Bitfinex {
}

const sticks = myCandles
.filter(function(candle) {
.filter(function(candle: any) {
return typeof candle.mts !== 'undefined';
})
.map(function(candle) {
.map(function(candle: any) {
return new ExchangeCandlestick(
'bitfinex',
mySymbol,
Expand Down
10 changes: 5 additions & 5 deletions src/modules/services.js → src/modules/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const ExchangeManager = require('./exchange/exchange_manager');
const Trade = require('../modules/trade');
const Http = require('../modules/http');
const Backtest = require('../modules/backtest');
const Backfill = require('../modules/backfill');
const Backfill2 = require('../modules/backfill');

const StopLossCalculator = require('../modules/order/stop_loss_calculator');
const RiskRewardRatioCalculator = require('../modules/order/risk_reward_ratio_calculator');
Expand Down Expand Up @@ -117,10 +117,10 @@ let tickerRepository;
let ordersHttp;
let pairConfig;

const parameters = {};
const parameters: {projectDir?: string} = {};

module.exports = {
boot: async function(projectDir) {
boot: async function(projectDir: string) {
parameters.projectDir = projectDir;

try {
Expand Down Expand Up @@ -313,7 +313,7 @@ module.exports = {
},

getNotifier: function() {
const notifiers = [];
const notifiers: any[] = [];

const config = this.getConfig();

Expand Down Expand Up @@ -652,7 +652,7 @@ module.exports = {
},

getBackfill: function() {
return new Backfill(this.getExchanges(), this.getCandleImporter());
return new Backfill2(this.getExchanges(), this.getCandleImporter());
},

createMailer: function() {
Expand Down
18 changes: 18 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"allowJs": true,
"checkJs": false,
"esModuleInterop": true,
"noImplicitAny": false,
"downlevelIteration": true,
"lib": ["esnext", "dom"],
"module": "commonjs",
"noUnusedLocals": true,
"outDir": "dist",
"skipLibCheck": true,
"strict": true,
"target": "esnext"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}