This repository has been archived by the owner on Oct 6, 2020. It is now read-only.
/
ConstantRiskLimitTool.java
363 lines (322 loc) · 15.2 KB
/
ConstantRiskLimitTool.java
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
* Copyright (c) 2014 Giorgio Wicklein <giowckln@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tradingTools;
import com.dukascopy.api.Configurable;
import com.dukascopy.api.IAccount;
import com.dukascopy.api.IBar;
import com.dukascopy.api.IConsole;
import com.dukascopy.api.IContext;
import com.dukascopy.api.IEngine;
import com.dukascopy.api.IHistory;
import com.dukascopy.api.IMessage;
import com.dukascopy.api.IMessage.Type;
import com.dukascopy.api.IOrder;
import com.dukascopy.api.IStrategy;
import com.dukascopy.api.ITick;
import com.dukascopy.api.Instrument;
import com.dukascopy.api.JFException;
import com.dukascopy.api.Period;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
/*
* This tool places a limit order with constant currency risk.
* Once you define your position currency risk, entry price and stop loss pips,
* this tool will calculate the right amount (lot size) to meet the defined currency risk.
* Since the order is of limit type, this strategy calculates and updates constantly
* that amount. This is needed because when a pending order gets filled, the variable amount
* of time which passed and the fluctuation of currency pairs let the original amount become obsolete.
* Other nice features, auto take profit price calculation based on risk:reward
* ratio, stop loss move to break even once the price reached 90% of target (TP).
* Use at your own risk.
*/
public class ConstantRiskLimitTool implements IStrategy {
// Configurable parameters
@Configurable("Instrument")
public Instrument instrument = Instrument.EURUSD;
@Configurable("Period")
public Period period = Period.DAILY;
@Configurable(value = "Buy order",
description = "Place a BUYLIMIT order (long)")
public boolean isBuyOrder = false;
@Configurable(value = "Sell order",
description = "Place a SELLLIMIT order (short)")
public boolean isSellOrder = false;
@Configurable(value = "Constant risk amount",
description = "Constant account currency risk for each trade")
public int constantCurrencyRisk = 100;
@Configurable(value = "Limit entry price",
description = "Entry price of the limit order")
public double entryLimitPrice = 0;
@Configurable(value = "Stop loss pips",
description = "Distance of stop loss from market entry in pips")
public double stopLossPips = 50;
@Configurable(value = "Reward risk ratio",
description = "Use 2 for risk:reward ratio of 1:2")
public double rewardRiskRatio = 2;
@Configurable(value = "B.E. on 90%",
description = "Move SL to break even once 90% of TP is reached")
public boolean moveSLBreakEven90 = false;
//this is a safety feature to avoid too big position sizes due to typos
private static final double maxPositionSize = 0.05;
private IEngine engine;
private IHistory history;
private IContext context;
private IConsole console;
private boolean orderIsOpen;
private double totalProfit;
private double totalCommission;
private String orderLabel;
private IEngine.OrderCommand orderCmd;
@Override
public void onStart(IContext context) throws JFException {
this.engine = context.getEngine();
this.history = context.getHistory();
this.context = context;
this.orderIsOpen = false;
this.console = context.getConsole();
this.totalProfit = 0;
this.totalCommission = 0;
this.orderLabel = "invalid";
//subscribe instruments
console.getOut().println("Strategy starting. Subscribing instruments...");
subscribeInstruments();
//check and setup order command
if (isBuyOrder ^ isSellOrder) {
if (isBuyOrder)
orderCmd = IEngine.OrderCommand.BUYLIMIT;
else
orderCmd = IEngine.OrderCommand.SELLLIMIT;
} else {
console.getErr().println("Invalid order side, please check only BUYLIMIT or SELLLIMIT");
return;
}
//check limit price
if (entryLimitPrice <= 0) {
console.getErr().println("Invalid limit order entry price");
return;
}
//calc profit pips
double takeProfitPips = stopLossPips; //risk:reward 1:1
if (rewardRiskRatio != 1) { //adjust reward if needed (custom risk:reward)
takeProfitPips *= rewardRiskRatio; //reward:risk
if ((takeProfitPips % 0.1) != 0) {
//round to 0.1 pip minimum requirement format, since not multiple of 0.1
takeProfitPips = (new BigDecimal(takeProfitPips)).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
//submit order
String direction = orderCmd.isLong() ? "long" : "short";
IOrder order = submitOrder(this.constantCurrencyRisk, orderCmd, stopLossPips, takeProfitPips);
console.getInfo().println("Order " + order.getLabel()
+ " submitted. Direction: " + direction
+ " Limit entry: " + entryLimitPrice
+ " Stop loss: " + order.getStopLossPrice()
+ " Take profit: " + order.getTakeProfitPrice()
+ " Amount: " + order.getAmount());
this.orderIsOpen = true;
}
@Override
public void onTick(Instrument instrument, ITick tick) throws JFException {
}
@Override
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if (instrument.equals(this.instrument) && period.equals(Period.ONE_MIN) && (orderIsOpen)) {
//check if any order meets the 90% B.E. SL move requirements
checkSLMoveBE();
//update amount to ensure constant risk for pending orders
updatePositionSize();
}
}
@Override
public void onMessage(IMessage message) throws JFException {
IOrder order = message.getOrder();
if (order != null) {
//handle only messages relative to the order managed by this instance
if (order.getLabel().equals(orderLabel)) {
if (message.getType() == Type.ORDER_CLOSE_OK) {
//update order variable on order close
this.orderIsOpen = false;
console.getInfo().println("Order " + order.getLabel()
+ " closed. Profit: " + order.getProfitLossInAccountCurrency());
//update profit/loss and commission
this.totalProfit += order.getProfitLossInAccountCurrency();
this.totalCommission += order.getCommission();
} else if (message.getType() == Type.ORDER_SUBMIT_REJECTED) {
//update order variable on order rejection
this.orderIsOpen = false;
console.getErr().println("Order " + order.getLabel() + " rejected.");
} else if (message.getType() == Type.ORDER_CHANGED_REJECTED) {
console.getErr().println("Order " + order.getLabel() + " change rejected.");
}
}
} else if ((message.getType() == Type.INSTRUMENT_STATUS)
|| (message.getType() == Type.CALENDAR)) {
//filter out
} else {
context.getConsole().getOut().println("Message: " + message.toString());
}
}
@Override
public void onAccount(IAccount account) throws JFException {
}
@Override
public void onStop() throws JFException {
console.getNotif().println("Strategy stopped. Profit: " + totalProfit +
" Commission: " + totalCommission +
" Net Profit: " + (totalProfit - totalCommission));
}
private IOrder submitOrder(int currencyRisk, IEngine.OrderCommand orderCmd, double stopLossPips, double takeProfitPips)
throws JFException {
double stopLossPrice, takeProfitPrice;
double positionSize;
//calc stop loss and take profit prices
if (orderCmd == IEngine.OrderCommand.BUYLIMIT) {
stopLossPrice = entryLimitPrice - stopLossPips * instrument.getPipValue();
takeProfitPrice = entryLimitPrice + takeProfitPips * instrument.getPipValue();
} else {
stopLossPrice = entryLimitPrice + stopLossPips * instrument.getPipValue();
takeProfitPrice = entryLimitPrice - takeProfitPips * instrument.getPipValue();
}
//calc position size
positionSize = getPositionSize(instrument, stopLossPips, currencyRisk, orderCmd);
//create order label
this.orderLabel = getLabel(orderCmd);
//submit order
return engine.submitOrder(orderLabel, instrument, orderCmd, positionSize,
entryLimitPrice, 5, stopLossPrice, takeProfitPrice);
}
private String getLabel(IEngine.OrderCommand cmd) {
return cmd.toString() + System.currentTimeMillis();
}
private double getPositionSize(Instrument pair, double stopLossPips, int constantCurrencyRisk, IEngine.OrderCommand orderCmd)
throws JFException {
//init symbols
String accountCurrency = context.getAccount().getCurrency().getCurrencyCode();
String primaryCurrency = pair.getPrimaryCurrency().getCurrencyCode();
String secondaryCurrency = pair.getSecondaryCurrency().getCurrencyCode();
//get exchange rate of traded pair in relation to account currency
double accountCurrencyExchangeRate;
String apCurrency = accountCurrency + "/" + primaryCurrency;
Instrument i;
if (primaryCurrency.equals(accountCurrency)) {
i = pair;
} else {
i = Instrument.fromString(apCurrency);
}
if (i == null) { //currency not found, try inverted pair
i = Instrument.fromInvertedString(apCurrency);
if (orderCmd == IEngine.OrderCommand.BUYLIMIT)
accountCurrencyExchangeRate = 1 / history.getLastTick(i).getAsk();
else
accountCurrencyExchangeRate = 1 / history.getLastTick(i).getBid();
} else {
if (orderCmd == IEngine.OrderCommand.BUYLIMIT)
accountCurrencyExchangeRate = history.getLastTick(i).getAsk();
else
accountCurrencyExchangeRate = history.getLastTick(i).getBid();
}
//calc currency/pip value
double pairExchangeRate;
if (orderCmd == IEngine.OrderCommand.BUYLIMIT)
pairExchangeRate = history.getLastTick(pair).getAsk();
else
pairExchangeRate = history.getLastTick(pair).getBid();
double accountCurrencyPerPip = pair.getPipValue() / pairExchangeRate *
100000;
if (!primaryCurrency.equals(accountCurrency))
accountCurrencyPerPip /= accountCurrencyExchangeRate; //convert to account pip value
//calc position size
double units = constantCurrencyRisk / stopLossPips * 100000 / accountCurrencyPerPip;
//convert to standard lots
double lots = units / 1000000;
//check position size safety
if (lots > maxPositionSize) {
console.getErr().println("Position size exceeds safety check, maxPositionSize constant"
+ " is " + maxPositionSize + " lots. But current position size is " + lots + " lots.");
lots = 0;
}
return lots;
}
private void checkSLMoveBE() throws JFException {
if (moveSLBreakEven90) { //is it user enabled
double percent90Profit = this.constantCurrencyRisk * 0.90 * rewardRiskRatio;
IOrder o = engine.getOrder(orderLabel);
if (o != null) {
if (o.getProfitLossInAccountCurrency() >= percent90Profit) {
double openPrice = o.getOpenPrice();
if (o.getStopLossPrice() != openPrice) {
o.setStopLossPrice(openPrice); // move SL to B.E.
console.getOut().println("Order " + o.getLabel() + ": SL moved to B.E.");
}
}
} else {
console.getErr().println("Order " + orderLabel + " not found");
}
}
}
private void updatePositionSize() throws JFException {
IOrder o = engine.getOrder(orderLabel);
if (o == null) {
console.getErr().println("Order " + orderLabel + " not found");
return;
}
if (o.getState() == IOrder.State.OPENED) {
double newPositionSize = getPositionSize(o.getInstrument(),
stopLossPips, constantCurrencyRisk, o.getOrderCommand());
//update amount
if (o.getAmount() != newPositionSize) {
o.setRequestedAmount(newPositionSize);
}
console.getOut().println("Order " + o.getLabel()
+ " updated position size: " + newPositionSize);
}
}
private void subscribeInstruments() {
//init list
Set<Instrument> instruments = new HashSet<Instrument>();
instruments.add(instrument);
//init symbols
String accountCurrency = context.getAccount().getCurrency().getCurrencyCode();
String primaryCurrency = instrument.getPrimaryCurrency().getCurrencyCode();
String apCurrency = accountCurrency + "/" + primaryCurrency;
//find complementary instrument
Instrument i;
if (primaryCurrency.equals(accountCurrency)) {
i = instrument;
} else {
i = Instrument.fromString(apCurrency);
}
if (i == null) { //currency not found, try inverted pair
i = Instrument.fromInvertedString(apCurrency);
}
if (i != instrument)
instruments.add(i);
//subscribe
context.setSubscribedInstruments(instruments, true);
}
}