Useful features from KimIV - page 4

 

More examples of how to use the SetOrder() function.

For clarity, we should select a symbol with a large minimum allowable level of stop loss/stake profit in pips. I have chosen AUDCAD, at which this level in my selected brokerage company for testing is 10 points.

1. Setting a BuyLimit order with lot 0.1, 5 pips below the current price. I purposely chose the order setting level lower than the minimum allowed level to get error 130 (Incorrect stops) and show how the SetOrder function will work it out.

SetOrder(NULL, OP_BUYLIMIT, 0.1, Ask-5*Point);

Contents of protocol (read from bottom to top):
2008.03.17 09:06:24 test_SetOrder AUDCAD,M5: removed
2008.03.17 09:06:24 stdlib AUDCAD,M5: removed
2008.03.17 09:06:24 stdlib AUDCAD,M5: uninit reason 0
2008.03.17 09:06:24 test_SetOrder AUDCAD,M5: uninit reason 0
2008.03.17 09:06:24 test_SetOrder AUDCAD,M5: open #21616412 buy limit 0.10 AUDCAD at 0.9180 ok
2008.03.17 09:06:15 test_SetOrder AUDCAD,M5: SetOrder(): Corrected price levels
2008.03.17 09:06:15 test_SetOrder AUDCAD,M5: Ask=0.919 Bid=0.918 sy=AUDCAD ll=0.1 op=Buy Limit pp=0.9185 sl=0 tp=0 mn=0
2008.03.17 09:06:15 test_SetOrder AUDCAD,M5: Error(130) set order: invalid stops, try 1
2008.03.17 09:06:15 stdlib AUDCAD,M5: loaded successfully
2008.03.17 09:06:14 test_SetOrder AUDCAD,M5: loaded successfully

The protocol shows that this function has tried to place a 0.9185 order (pp=0.9185) but the trading server did not accept such order and returned error 130. Then the function corrects the order setting level according to the minimum allowable level and performs the next trade attempt that ends successfully. The order is set at 0.9180.

2. Setting a BuyStop order with lot 0.3 at 6 pips above the current price with a stop of 9 pips

SetOrder(NULL, OP_BUYSTOP, 0.3, Ask+6*Point, Ask+(6-9)*Point);

Contents of the protocol (read from the bottom upwards):
2008.03.17 09:27:36 test_SetOrder AUDCAD,M5: removed
2008.03.17 09:27:36 stdlib AUDCAD,M5: removed
2008.03.17 09:27:36 stdlib AUDCAD,M5: uninit reason 0
2008.03.17 09:27:36 test_SetOrder AUDCAD,M5: uninit reason 0
2008.03.17 09:27:36 test_SetOrder AUDCAD,M5: open #21617419 buy stop 0.30 AUDCAD at 0.9209 sl: 0.9195 ok
2008.03.17 09:27:26 test_SetOrder AUDCAD,M5: SetOrder(): Corrected price levels
2008.03.17 09:27:26 test_SetOrder AUDCAD,M5: Ask=0.9198 Bid=0.9188 sy=AUDCAD ll=0.3 op=Buy Stop pp=0.9204 sl=0.9195 tp=0 mn=0
2008.03.17 09:27:26 test_SetOrder AUDCAD,M5: Error(130) set order: invalid stops, try 1
2008.03.17 09:27:26 stdlib AUDCAD,M5: loaded successfully
2008.03.17 09:27:25 test_SetOrder AUDCAD,M5: loaded successfully

This example shows how the order setting level has changed from 0.9204 to 0.9209. At the same time, the level of stop has remained unchanged at sl=0.9195. That is, the stop in pips has increased from 9 to 14.

 

3. Setting a SellLimit order with 0.5 lot at 8 points above the current price with a stop of 9 points and a take order of 7 points

SetOrder(NULL, OP_SELLLIMIT, 0.5, Bid+8*Point, Bid+(8-9)*Point, Bid-(8+7)*Point);

Contents of the protocol:
2008.03.17 10:38:50 test_SetOrder AUDCAD,M5: removed
2008.03.17 10:38:50 stdlib AUDCAD,M5: removed
2008.03.17 10:38:50 stdlib AUDCAD,M5: uninit reason 0
2008.03.17 10:38:50 test_SetOrder AUDCAD,M5: uninit reason 0
2008.03.17 10:38:49 test_SetOrder AUDCAD,M5: open #21620553 sell limit 0.50 AUDCAD at 0.9190 sl: 0.9201 tp: 0.9179 ok
2008.03.17 10:38:40 test_SetOrder AUDCAD,M5: SetOrder(): Corrected price levels
2008.03.17 10:38:40 test_SetOrder AUDCAD,M5: Ask=0.919 Bid=0.918 sy=AUDCAD ll=0.5 op=Sell Limit pp=0.9188 sl=0.9197 tp=0.9179 mn=0
2008.03.17 10:38:40 test_SetOrder AUDCAD,M5: Error(130) set order: invalid stops, try 1
2008.03.17 10:38:40 stdlib AUDCAD,M5: loaded successfully
2008.03.17 10:38:39 test_SetOrder AUDCAD,M5: loaded successfully

This example again attempts to set a limit order too close to the market. The order setting level has been adjusted upwards by 2 pips from 0.9188 to 0.9190. The stop level has also been adjusted, but by 4 points from 0.9197 to 0.9201. Only Take level has remained unchanged, which increased it from 9 to 11 pips.

I think that's enough examples. They are already quite difficult to understand. What conclusions can be drawn?
1. The function will do its best to complete its task, i.e. it will try to set an order. It will adjust the levels to the changing market and try to do its job again and again.
2. The stop order setting level adjustment leads to an increase of the stop level in points relative to the setting price. This is due to the fact that the stop order level remains in place and the order setting level is moved away from the stop level. The level of BuyStop order is shifted upward and SellStop order is shifted downward. These manipulations with the order setting level increase the stop size in points by the value of the order setting level adjustment.
3. The adjustment of the limit order setting level results in the increase of take profit level in points relatively to the setting price. This is implemented in the following way. The tees remain in place while stops and setup levels are shifted upwards for BuyLimit and downwards for SellLimit. The size of take in points increases by the value of order setting level correction.

Warning! I have changed the code of the SetOrder function by swapping a few lines. The old post cannot be edited, so I am pasting the corrected function here. Also attached is a script for online testing of SetOrder function.


Files:
 

In order to speed up the publication of the ModifyOrder function, I decided to switch to the position functions for a while, and then go back to the order functions and finish with them.

Note!
I definepositions as OP_BUY and OP_SELL trading operations. Positions are opened and closed.
I call trade operations OP_BUYLIMIT, OP_BUYSTOP, OP_SELLLIMIT and OP_SELLSTOPas orders. Orders are placed and deleted. If an order is triggered, it becomes a position.

The ExistPositions() function.

This function is intended for checking if there are open positions of buying or selling. Similar to the ExistOrders function. By default, it checks all positions: current and others. You can refine the selection with a combination of filters - function parameters:

  • sy - Imposes a restriction on the name of the instrument. The default parameter is "" - no restriction, i.e. any instrument. If you pass NULL, the position selection will be limited to the current instrument.
  • op - places a restriction on position type (Buy/Sell). By default, there is no constraint, that is, any position type is checked. Valid values for this parameter are -1, OP_BUY and OP_SELL.
  • mn - Applies restriction on the identification ("magic") number of the position. By default there is no constraint, i.e. the position with any magic number is checked.
  • ot - Applies restriction on position opening time. It checks if the position will be opened later than the value of this parameter. No constraint by default, i.e. any position with any opening time is checked.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 06.03.2008                                                     |
//|  Описание : Возвращает флаг существования позиций                          |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    ot - время открытия             ( 0   - любое время открытия)           |
//+----------------------------------------------------------------------------+
bool ExistPositions(string sy="", int op=-1, int mn=-1, datetime ot=0) {
  int i, k=OrdersTotal();
 
  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (ot<=OrderOpenTime()) return(True);
            }
          }
        }
      }
    }
  }
  return(False);
}
 

Examples of how to use the ExistPositions() function.

1. Check the existence of any position

ExistPositions();

2. Check existence of any position on the current chart symbol

ExistPositions(NULL);

3. Check existence of purchase on any instrument

ExistPositions("", OP_BUY);

4. Check if there is a sale with magic number 123456 on EURUSD

ExistPositions("EURUSD", OP_SELL, 123456);

5. Check existence of any position with opening time not earlier than 15 minutes ago

ExistPositions("", -1, -1, TimeCurrent()-15*60);

The trailer contains a script for testing the ExistPositions function. The first four examples are commented out.

Files:
 
Sorry, but neither OrderSet_1 nor OrderSet_2 work! It generates errors - it won't compile! What do I do?
 
SoloEgoist:
Sorry, but neither OrderSet_1 nor OrderSet_2 work! It generates errors - it won't compile! What do I do?
The OrderSet_1 or OrderSet_2 files are source codes for OrderSet function in different versions. Just the source code, that's all. They won't compile or properly execute (without errors). In order to get at least some results, you must also create a working environment that uses the OrderSet function. I have created an example of such a working environment in test_SetOrder.
 
Thank you. I see - I'll try, I just don't know much of the language.
 

Functions and ways of working with date and time would come in handy...

For example:
- subtract 2 hours from the current time
- X days to expiration...

Also... I don't know if this is relevant... :(

Functions for statistics. For example:
- how many hourly candlesticks at 21:00 every monday
- of which: 215 bullish, 245 bearish
- of bullish candlesticks: min. 12 pips max 54 pips
- etc...

or
- the low of every first 15H candle of the day is higher/lower than the second X number of times

It's not the functions themselves that are important, but how they are created, and it's easier to implement your own functions,
while learning how to program...
I'm complaining once again :))) Sometimes a lot of things are not very clear, and books on C may help.
You may of course read them, but do you really need to fill your head with unnecessary information, focusing only on µl4?
what kind of obscurity? for example this: ||

 
kombat:

Functions and ways of dealing with date and time would come in handy...

For example:
- subtract 2 hours from the current time
- X days left until expiry...

...


you don't need to write such a function - there is a very simple solution!


int gHour = 2;
datetime gTwoHour ;


gTwoHourTime = TimeCorrent() - ((86400)/24) * gHour ); // 2 hours
gTwoHourTime = TimeCorrent() - 7200; // the same but without load calculations

i.e. we get 86400 ticks in a day

so 2 hours = 7200 ticks, i.e. 86400/24 * 2 = 7200
1 hour = 3600; etc.
 
kombat:

Functions and ways of working with date and time would be useful.

Functions for statistics. For example:
- how many candlesticks of 21:00 every Monday
- of which: 215 bullish, 245 bearish
- of bullish candlesticks: min. 12 pips max 54 pips
- etc...

or
- the low of every first 15H candle of the day is higher/lower than the second X number of times

It's not the functions themselves that are important, but how they are created, and it's easier to implement your own functions,
while learning how to program...

Duly noted... :-)

kombat wrote (a):
I'll complain again :))) sometimes a lot is not very clear, and they say that C books will help.
They point out that a lot of C books will help. Of course, you can read them, but do you really need to fill your head with unnecessary information, focusing only on µl4?
what kind of obscurity? for example this: ||

It's a logical OR. Let me explain it by example. The "If x>2 or x<-3, then x=5" expression in MQL4 will have the following form

if (х>2 || х<-3) х=5;
Reason: