Max Spread and Max Slippage parameters for opening trades for exported EAs

Hi. 



I believe an absolutely essential feature we need when exporting our stategies to run in MT4 and MT5 is a parameter that sets a max spread and max slippage for opening a trade. If this limit is exceeded, the EA should not open a trade.


I feel very exposed not having this as part of exported EAs because broker spreads can suddenly widen a lot very rapidly during events (as per screenshot attached with 2 brokers compared side by side).


I really don't want to have trades open at 53.6 pips on AUD CAD for example!


I will have to add this myself to exported code in the mean time, which will be time consuming, but absolutely ESSENTIAL for managing my risk and would love to see this as part of SQX!

Attachments
MASSIVE SPREADS.png
(517.73 KiB)
  • Votes +13
  • Project StrategyQuant X
  • Type Feature
  • Status Refused
  • Priority Normal

History

JK
#1

Insanity82007

11.02.2020 11:25

Task created

JK
#2

Insanity82007

11.02.2020 11:27
Voted for this task.
h
#3

hankeys

11.02.2020 12:20
Voted for this task.
b
#4

bentra

11.02.2020 19:22


As for max spread... I agree, max spread is a deal breaker but this is a Duplicate:
https://roadmap.strategyquant.com/tasks/sq4_4184

As for slippage maximum. This is not possible for ECN transactions I don't think. The slippage variable is ignored trading on an ECN broker with MT4 for instance. But I can say from experience, max spread does help limit slippage.

JK
#5

Insanity82007

18.04.2020 09:31
I hope the results of COVID and the massive widening of spreads across so many asset classes makes it obvious to see why this feature is essential for us to have in SQX strategies before we trade them in a live environment! 


Anyone currently trading gold or incides will be getting murdered out there with current spreads without this failsafe!

IH
#6

clonex / Ivan Hudec

18.04.2020 09:32
Voted for this task.
fG
#7

Gianfranco

18.04.2020 09:54
Voted for this task.
l
#8

ludvick

18.04.2020 10:06
Voted for this task.
Gl
#9

Gui

18.04.2020 10:48
Voted for this task.
Rr
#10

Partizanas

18.04.2020 11:13
Voted for this task.
h
#11

hankeys

19.04.2020 08:55
some slippage control is already in the MQL4 code implemented, but if this works who knows


int sqMaxEntrySlippage = 5;          //Max tolerated entry slippage in pips. Zero means unlimited slippage

int sqMaxCloseSlippage = 0;          //Max tolerated close slippage in pips. Zero means unlimited slippage       

bool autoCorrectMaxSlippage = true;  //If set to true, it will automatically adjust max slippage according to symbol digits (*10 for 3 and 5 digit symbols)  


this is original settings in the MQL4 code, but its without extern, so you need to set it manually by editing the MQL code itself or template in the SQX


JK
#12

Insanity82007

19.04.2020 11:00
I'm not surprised to see this implemented in the code as the MQL4 OrderSend function includes a slippage parameter natively. Thanks for finding this and pointing this out! Good find!
h
#13

hankeys

19.04.2020 11:10
but for widening spreads there is nothing
DB
#14

Enyx

19.04.2020 11:12

As a workaround: Instead of manually updating these values consider updating the MQL code generation template(s) \extend\Code\MetaTrader{4,5}\Main.tpl. (until next update overwriting it)


In any case check error handling logic for generated EA..


But I agree there should be a way to configure such parameters externally.


DB
#15

Enyx

19.04.2020 11:14
Voted for this task.
DB
#16

Enyx

19.04.2020 11:16

Also you may "try" with template which has a spread filter....


Long term, there is an internally risk class filters that need to be enabled by SQX developers.. No idea why it stay dormant code..

DB
#17

Enyx

19.04.2020 11:41
I believe best way (without official developer support) is additional trade option. Also I think these "internal" variables can be modified from the trading option as well. I will try to do something as I need that too.
DB
#18

Enyx

19.04.2020 23:35

Attachment Capture1.png added

Attachment Capture2.png added

A new maximum spread trading option is ready. I will publish it during next week.


Just thinking. Is it good idea to export trade option's value automatically from strategy's config ?


JK
#19

Insanity82007

20.04.2020 02:50
This looks awesome Enyx. How does it work with pending orders e.g. stop or limit orders?
DB
#20

Enyx

20.04.2020 11:25
Trading options are evaluated on bar opening  (simple incomplete answer). This simple "filter" is checking current spread (on Main chart) and preventing order creation at this specific moment. Any previously placed orders on the platform will be executed as usual. In short, it will may not help with these. In any case there is no easy or ideal solution for these kind of order. Or may be someone have a better suggestion?
h
#21

hankeys

20.04.2020 14:38
slippage control and spread control must be done upon TRADE opening, not on pending orders


and for me its nonsense to implement it to the SQX itself- because SQX is only a backtester, he cant see the future, not the real tick data from brokers we are getting


so for me SQX is finished by my needs - i have some major spread and slippage setting, where i put some everage value i can see on real account and thats it


spread and slippage control must be solved in the MQL code only

DB
#22

Enyx

20.04.2020 15:14

makes sense. spread filter (slippage will be additional trading option) is in place in both mql4/5 and effective in SQX  itself (has to be there for consistency or 0=off). 


Option 1)


so does it make sense to export spread size filter value as EA parameter or just set it to 0=off (manually adjust).


or..


Option 2)


spread size > 0 .. export this value with EA (as EA parameter)

spread size = 0 .. export this value with EA (0=off) (as EA parameter)

spread size < 0 .. export this value from test strategy spread size (as EA parameter). Tick data testing here is issue as spread is variable.


I know none of these is optimal...


suggestions welcome.

h
#23

hankeys

20.04.2020 16:59
for market strategies and spread the logic could be simple - not enter if real spread value > set value


but what for slippage? - because slippage happen after open trade, not before and you can compute the slippage only if you are already in the trade - you can do only 1 or 2 things - close open trade immediately or move SL and TP values and correct their values to keep strategy logic untouched


but what to do with pending orders? because you will put pending order to the place and you know only the spread - what now? pending order will be placed when spread will have normal value, than widening occurs, what now? delete the pending and prevent the possible future trade? because final enter to the trade could be on times with normal spread


this taks has many answers and i am seeing it very easy - widening spread and slippages will be with us, we cant do anything about it...so i am trading no matter what spread is or what slippage i get...and i am counting on real account, that my results will be 50% of what i see in the backtest

JK
#24

Insanity82007

21.04.2020 10:00
It could work like this for pending orders:

  1. If spreads exceed the threshold, all pending orders are immediately cancelled
  2. Another setting is used to determine how long spreads have operated below the threshold e.g. 5 minutes or 15 minutes AND other signals have not invalidated the condition for pending orders AND the price has not moved through the pending order price. If these conditions are satisfied, the pending orders are re-opened. 

This should not be hard to implement as the code runs on each and every tick.


As far as slippage goes, there's not much we can do beyond using a broker that allows slippage thresholds or renting a VPS or dedi as close as possible to the broker's servers and using a reputable broker. 


It would still be good to include the slippage option with SQX MQL exports as this function does exist, but a warning message with a caveat should pop-up when exporting this code to MQL4 or MQL5 warning the user that not all brokers will honor this setting and this is NOT the responsibility of SQ devs.

h
#25

hankeys

21.04.2020 15:30
sounds good to me


could devteam describe what slippage control right now do in the code exactly?

DB
#26

Enyx

21.04.2020 20:55

(I am not from dev team :) In terms of exported EA (only MT).


MT4 - It's managed by good old OrderReliabler.There is little done than passing slippage to MT API and reporting. A little extra logic from library.

MT5 - Just a simple passthrough to MT API.. huh.


That'it

DB
#27

Enyx

21.04.2020 21:49

Attachment TO.png added

Attachment TO2.png added

Attachment SQExtension-TO-MaximumSpreadSlippage.sxp added

** USE THIS CODE IN COPY OF DEVELOPMENT ENVIRONMENT **

** PREVIEW **


** You have been warned ** Extension below is adding a new global trading options and new/retested strategies will require the supporting classes. will not open on SQX installation without this package. ** You have been warned **


How to test..


Make a copy of your SQX folder so you can delete it after.. Pls.


Import SXP file : Code editor -> Import/Export -> Import Extension


What does it do.


Spread filter is the maximum market spread  in pips allowing to open a position. Filter in SQX simulation and exported to EA. Specify 0 for unlimited

 if current spread > MaxSpread do not submit order..

 Already sumitted orders are not affected. Already under platfrom control.

Maximum slippage -> Does nothing in SQX simulation (intentionally). Allows easy way to override EA internal variables sqMaxEntrySlippage and sqMaxCloseSlippage. SQX defaults assumed.


//+------------------------------------------------------------------+
// -- SQ Variables
// - add word "input" in front of the variable you want
//   to make configurable
//+------------------------------------------------------------------+
                                                                              
int sqMaxEntrySlippage = 5;          //zero means unlimited slippage
int sqMaxCloseSlippage = 0;          //zero means unlimited slippage


-----------

^^^^

^^^ Override variable above without template changes

^^^


extern string smslpd = "----------- Maximum Slippage -----------";
extern int MaxEntrySlippage = 5; // Maximum entry slippage in pips
extern int MaxCloseSlippage = 0; // Maximum close slippage in pips


KL
#28

kainc301

21.04.2020 23:09
@Eynx Do you have a link to any guides as to how to create SQX extensions? I'd love to mess around with one if it means I can help get features implemented
JK
#29

Insanity82007

22.04.2020 12:20
Enyx. This is cool. Thanks for making it! How will this affect importing SQX trategies into Quant Analyzer?
FC
#30

Kenzo105

22.04.2020 12:39
Voted for this task.
DB
#31

Enyx

22.04.2020 14:12

@keinc301: I had a rough journey as for my docs are thin but you can probably start from here (may not be exhaustive):


1) Some examples here: https://strategyquant.com/codebase

2) In built-in code editor in Snippets sub-dir are the java the implementation for all blocks/trade options/MM/colums/etc used in simulation engine. So look around in the examples. Code editor has auto-complete (might help). Some SQX API https://strategyquant.com/qa_api/  Not sure how accurate is this one

Export templates are in "code" sub-directory. For the record .tpl files are apache Freemaker .

3) I personally use Java IDE with debugger. it's doable but it's complete dark magic. But if you are skilled enough you should be able to setup a project and attach to java VM so you can debug public code. It's possible to debug internals (i do that) but even do not ask me on this..

4) For real plug-ins (like Builder,Retested,Custom workflow blocks).. Oh, do not even start. Square of difficulty of item 3). I have piloted my plugin, works fine but you should be paid to get through this pain.. seriously.

5) Persistence, do not give up. I could not get help for SQX team. Asked for that..


Once you get used to this complete mess is OK :)

DB
#32

Enyx

22.04.2020 14:20

Attachment SQExtension-TO-MaximumSpreadSlippage_v2.sxp added

@Insanity82007:


Slippage does nothing in SQX simulation. it's about MT export

Spread is simple filter. If on bar update current spread > MaxSpread do not allow creating new orders. Filters both SQX sim and MT EA


You can always update login in code edit, it's that simple. Check content of sxp file (it's zip)


Java Code:

@Override
public boolean OnBarUpdate(StrategyBase strategy) throws Exception {
if (MaximumSpread <= 0) return true;

String symbol = strategy.Symbol;

// Get current spread in pips
double spread = strategy.convertRealPriceToPips(
symbol,
Math.abs(strategy.MarketData.Chart(symbol).Ask() - strategy.MarketData.Chart(symbol).Bid())
);

// Allow trades only if spread is less or equal to maximum permitted
return (spread <= SQUtils.round(MaximumSpread, 1));
}

MQL Code:


virtual bool onBarUpdate() {
if(MaximumSpread <= 0) return true;

// Resolve main chart symbol
string symbol = correctSymbol("${doc.StrategyFile.Strategy.Datas.data[0].symbol}");

// Get current spread in pips
double spread = sqConvertToPips(symbol, sqGetAsk(symbol) - sqGetBid(symbol));

// Allow trades only if spread is less or equal to maximum permitted
if(spread > NormalizeDouble(MaximumSpread, 1)) return false;

return true;
}
MF
#33

Mark Fric

26.11.2020 11:10

Status changed from New to Refused

after a consideration we are refusign this feature. SQ is a strategy generator, it cannot cover every aspect of live trading. 


This is something out of its scope, you can hire a programmer to create a snippet for you to put to your strategies.

JB
#34

DiscoGolf

02.01.2021 20:46
Voted for this task.
JB
#35

DiscoGolf

02.01.2021 21:03
Mark, I can understand your perspective about spread control being beyond the scope of SQX.  However, your competition "Forex Strategy Builder Pro", a product that I own and have used extensively, has a "Max Spread" feature that I use on EVERY EA.  It's extremely useful for keeping me out of stupid trades both during the swap (where spreads on even common pairs at my broker reach 15-30 pips) as well as during news releases.  


I purchased SQX to further diversify my strategies, as well as for the advanced strategy portfolio management features that SQX offers, and I look forward to exploring the software further over the coming months and years.  It's my bad for not looking closer and finding this feature missing before I pulled the trigger.  I plan on using the "Limit Time Range" feature as a work around to disallow trades during the swap, however, I'm in agreement with the other voters in this thread that adding spread control is not just a "nice to have", it's a "must have" for Forex.  To me this seems like an easy feature to include in a software that aims (among other things) to keep it's users from having to "program things" or "hire a programmer".

m
#36

mattedmonds

03.01.2021 05:00
Not sure what everyone is concerned about, this already exists.


I set spread < 1.5 pips on opening and closing every trade. It works well.


I also adjust the code to max slippage 0.3 pips and haven't noticed any issues with it. 


I note the code includes adding the trade spread to the comments, but it doesn't work. This would be really useful to have working properly.

b
#37

bentra

03.01.2021 17:17
Voted for this task.

Votes: +13

Drop files to upload

or

choose files

Max size: 5MB

Not allowed: exe, msi, application, reg, php, js, htaccess, htpasswd, gitignore

...
Wait please