-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
IBKRConnection.ts
198 lines (152 loc) · 5.22 KB
/
IBKRConnection.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import * as _ from 'lodash';
import chalk from 'chalk';
import ibkr from 'ib';
import { IB_HOST, IB_PORT } from '../config'
import { publishDataToTopic } from '../events/IbkrEvents.publisher';
import { IBKREVENTS, IbkrEvents } from '../events';
import { ConnectionStatus } from './connection.interfaces';
import AccountSummary from '../account/AccountSummary';
import { Portfolios } from '../portfolios';
import OpenOrders from '../orders/OpenOrders';
import includes from 'lodash/includes';
const appEvents = IbkrEvents.Instance;
// This has to be unique per this execution
const clientId = _.random(100, 100000);
/**
* Global IBKR connection
* @singleton class
*/
export class IBKRConnection {
public status: ConnectionStatus = null;
public IB_PORT: number = IB_PORT;
public IB_HOST: string = IB_HOST;
private static _instance: IBKRConnection;
public ib: any;
public static get Instance() {
return this._instance || (this._instance = new this());
}
private constructor() { }
/**
* init
*/
public init(host: string, port: number) {
if (!this.ib) {
this.ib = new ibkr({
clientId,
host,
port
});
this.listen();
}
}
/**
* initialiseDep
* Call/Initialize Account summary -> Portfolios -> OpenOrders
*/
public initialiseDep = async (): Promise<boolean> => {
try {
// 1. Account summary
console.log('1. Account summary')
const accountSummary = AccountSummary.Instance;
accountSummary.init();
await accountSummary.getAccountSummary();
// 2. Portolios
console.log('2. Portolios')
const portfolio = Portfolios.Instance;
await portfolio.init();
await portfolio.getPortfolios();
console.log('3. OpenOrders');
const openOrders = OpenOrders.Instance;
openOrders.init();
await openOrders.getOpenOrders();
return true;
}
catch (error) {
console.log('error initialising IBKR', error);
return false;
}
}
/**
* On listen for IB connection
*/
private listen(): void {
const self: IBKRConnection = this;
function disconnectApp() {
publishDataToTopic({
topic: IBKREVENTS.DISCONNECTED,
data: {}
});
self.status = IBKREVENTS.DISCONNECTED;
return console.error(IBKREVENTS.DISCONNECTED, chalk.red(`Error connecting client => ${clientId}`));
}
// Important listners
this.ib.on(IBKREVENTS.CONNECTED, function (err: Error) {
async function connectApp() {
if (err) {
return disconnectApp();
}
console.log(chalk.blue(`.................................................................`));
console.log(chalk.blue(`...... Connected client ${clientId}, initialising services ......`));
// initialise dependencies
const connected = await self.initialiseDep();
if (connected) {
publishDataToTopic({
topic: IBKREVENTS.CONNECTED,
data: {
connected: true
}
});
self.status = IBKREVENTS.CONNECTED;
console.log(chalk.blue(`...... Successfully running ${clientId}'s services ..`));
return console.log(chalk.blue(`.....................................................`));
}
disconnectApp();
}
connectApp();
})
this.ib.on(IBKREVENTS.ERROR, function (err: any) {
const message = err && err.message;
console.log(IBKREVENTS.ERROR, chalk.red(err && err.message));
if (includes(message, 'ECONNREFUSED') || err && err.code === 'ECONNREFUSED') {
return disconnectApp()
}
})
this.ib.on(IBKREVENTS.DISCONNECTED, function (err: Error) {
console.log(IBKREVENTS.DISCONNECTED, chalk.red(`Connection disconnected => ${clientId}`));
return disconnectApp();
});
// connect the IBKR
this.ib.connect();
// App events
appEvents.on(IBKREVENTS.PING, () => {
// If we have the status
if (self.status) {
// PONG the current status
publishDataToTopic({
topic: self.status,
data: {}
});
}
})
}
/**
* getIBKR instance
*/
public getIBKR(): any {
return this.ib;
}
/**
* disconnectIBKR
*/
public disconnectIBKR(): void {
this.status = IBKREVENTS.DISCONNECTED;
try {
console.log(chalk.keyword("orange")(`IBKR Force shutdown ${clientId} 😴😴😴`));
this.ib.disconnect();
}
catch (error) {
console.log(IBKREVENTS.ERROR, chalk.red(error))
}
}
}
export default IBKRConnection;