[WARNING CLOSED!] Any newbie question, so as not to clutter up the forum. Professionals, don't go by. Can't go anywhere without you. - page 554

 
drknn >>:

artmedia70, Проходим по всем ордерам и суммируем их профиты. Если результирующий профит больше нуля или больше некой, заранее заданной величины, то закрываем все позы.

Попробуйте код закрытия всех ордеров сделать самостоятельно.

Подсказка: Для цикла, в котором все ордера будут закрываться, нужно направление перебора ордеров делать обратным - точно так, как я это сделал в вышеприведённом коде. А именно - от последнего ордера к первому. Если поменять направление перебора, то в цикле будут закрыты не все ордера. Например, ордер, который стоит в списке первым, будет закрыт и в результате на его место встанет другой. А поскольку счётчик цикла увеличился на единицу, то другой ордер из этой строчки списа будет пропущен.

Thank you. That's not quite what I need, or rather not at all... I need to do a counter closure of one loss by one or more profitable ones to get equity out of a drawdown.
 

Well, it's still a loop.

Declare a variable of type double.

We pass all orders. If the order profit is smaller than the one in double, we will store this profit in it. Thus, after the loop, this variable will contain the value of the smallest profit (that is, the largest loss of the available ones). If we save in the arrays both the ticket of the current losing order and those orders that have more than zero profit, and the total profit of the orders that have a positive one, we can decide everything (what orders to use and how much to cover) in one function.

 
drknn >>:

Ну всё равно цикл.

Объявляем переменную типа double.

Проходим по все ордерам. Если профит ордера меньше чем тот, что в double, то запоминанем в неё этот профит. Таким образом после цикла в этой переменой лежит значение самого маленького профита (читай самый большой убыток из имеющихся). Если параллельно запоминать в массиывы и тикет текущего убыточного ордера и те тикеты ордеров, у котороых профит больше нуля, и суммарный профит ордеров, у которых он положительный, то можно всё решение (какими ордерами и сколько перекрывать) принять в одной функции.

Sens!!! Now that's a thing! I'm going to go poke around... :)
 

Here's another question...
Friends! Please tell me, how is it possible not to buy at the very top of the up-movement and not to sell at the very bottom? The signal to buy still exists, but it is close to the reversal, and it (the Expert Advisor) wham... and buys. The position turns out to be loss-making. How to filter it?

I've tried all sorts of different indulgences - all not the same...

Maybe someone has already faced with this problem, or rather a problem? How it can be solved, even a half-word, please ...
Endless Profits to all!

 
artmedia70 >>:

А вот ещё вопросик...
Други! Подскажите, плиз, каким образом возможно не покупать на самом верху движения вверх и не продавать на самом донышке. А то получается, что сигнал на покупку ещё присутствует, но уже близко к развороту, а он (советник) хрясь... и покупает. Позиция оказывается убыточной. Как бы фильтровать енто дело, а???

Перепробовал уже уйму всяческую различных индюков - всё не то...

Мож кто сталкивался ужо с данной проблемой, даже, скажем точнее - проблемищей? Как её возможно решить, хоть пол-словом обмолвитесь, пожалуйста...
Всем профитов нескончаемых!


As an option - alternate trades. For example, we trade on the basis of - direction of moving + price location (I will tell you right away the system is loss-making, but it illustrates the approach well). For example. Write in the code: SignalBuy=false; SignalSell=false; - null signals. Then we check: a signal to buy is moving upwards and the price is higher than the moving average. Therefore SignalBuy=true; if the moving downwards and the price is lower than the moving one, then SignalSell=true; we should also write a condition: if there are no orders in the market and the Buy position is true and the last order in the history is Buy, then SignalBuy=false; - i.e. we drop the Buy signal since the long order has just been closed. The same is true for the short positions. What are we trying to achieve? If the slip is reversed and the price breaks through, an appropriate order will be opened. Then the Expert Advisor will wait for the opposite signal. This means that if the long position is closed almost at the very top of the trend, then at this point, the long will not be opened, because the EA will be in a state of waiting for the signal to open the short.

I think the principle is clear.

 
drknn >>:


Как вариант - чередовать сделки. Например, торгуем по признаку - направление скользящей + местонахождение цены (скажу сразу система убыточна, но хорошо иллюстрирует подход). Например. Пишем в коде: SignalBuy=false; SignalSell=false; - обнулили сигналы. Далее проводим проверку: сигнал к покупке - скользящая вверх и цена выше скользяшей. Следовательно SignalBuy=true; если скользящая вниз и цена ниже скользящей, то SignalSell=true; Дале пишем условие: если ордеров в рынке нет, и при этом сигнал к покупке имеет положение "истина" и при этом последний ордер в истории - Buy, то SignalBuy=false; - то есть, сбрасывем сигнал к покупке, так как только что лонговый ордер был закрыт. То же самое с шортовыми позициями. Чего мы этим добьёмся? При перевороте скользящей и пробитии ценой будет открыт соответствующий ордер. Далее советник будет ждать противоположного сигнала. Это значит, что если лонговая поза закрылась почти на самом верху тренда, то в этой точке лонг уже не откроется, так как советник встанет в состояние ожидания сигнала открыть шорт.

Думаю, принцип понятен.

Yes, of course, thank you, the principle is clear, but in my TS it will be even more unprofitable... I trade in almost all TFs at once (from M5 to D1), and in each TF several of my TS are working simultaneously... So, on M5 I collect everything I can during price movement... Here is the problem... The buy signal lasts until the reversal. Same for Sell. Of course, it may gather enough profit on the move, but these losing positions opened on price peaks and troughs either eat up all the profits of the movement or... (if you don't close them, but sit tight) ... eat up all the margin. So how do you cut them off with something... ...to cut off those peaks and bottoms so they don't have a signal...
 
artmedia70 >>:
Да, конечно, спасибо, принцип понятен, но в моей ТС он будет ещё более убыточен. У меня торговля идёт сразу почти по всем ТФ (от М5 до D1) и на кждом ТФ несколько своих ТС одновременно пашут... Так вот на М5 у меня собирает по ходу движения цены всё, что можно... Вот здесь и загвоздочка... Сигнал на Бай длится до самого разворота. Также и на Селл. По движению он собирает конечно достаточно, но эти убыточные позиции, открытые на пиках-донышках либо съедают всю прибыль от движения, либо... (если их не закрывать, а пересиживать) ... жрут всю маржу. Вот как бы их подрезать чем-нить... эти пики-дондышки, чтоб сигнала уже не было...


>> Each TF has its own trading system.

It means that if we want advisors with different trading systems not to interfere with each other's work, then we use a magik - for each TS such that it is different from the magik of other TS. This will allow the EA to see only its own orders. Then we go through the orders and if the order with the specified magic number is already present in the market (for example, buy), then we nullify the signal to go long. Or, if the last long order is the last in the history, then we also null it and wait for the short.

Otherwise, if we want our EA to interfere with other trading systems of the same currency pair, we will not consider the Magic number in the order loop. The further logic of simplifying positions is the same. But there is one subtle point here. If 1 EA interferes with another EA, we need to prepare another EA for a situation where it will suddenly notice that its order has disappeared - the EA should be able to react properly to this - not immediately open a new order thoughtlessly, but analyze, for example, the same trading history.

 

You say that your signal stretches all the way to the U-turn. But there is a way around that as well. There are no orders in the market - we check for a signal. The signal appears - we open a position, remove the signal flag(zeroed the variable) and do not check further for a signal (e.g. long) until the opposite signal appears (short). This way, the flag on the presence of a signal of a given type will last for only a few seconds at all - the flag is set, the order is placed, the flag is removed - we wait for the opposite signal to occur. The opposite has arisen, the flag of the opposite signal is set and we set the flag, which gives the good to track the signals that were forbidden to track before.

Start the Expert Advisor (not the start() function, but just the beginning of work):

- We give permission to track both long and short signals.

We have a long signal:

- Allow us to track the shorts signals.

- We set the long order, and if the order has already been set, then

- Remove the flag which allows us to track the long signals.

The short signal has been triggered

- If we have the option to reverse orders, then close the long order and set the short order

- Establish a flag which allows us to track long signals and remove the flag which allows us to track short signals.

Generally speaking, flags are switches. We could also design switches instead of switches. In this case, the Expert Advisor starts working on the principles of a cybernetic automaton that has a memory of the state it is in. This can be achieved, for example, by declaring an integer variable and assigning state numbers to it. For example, in the initialization block we write

Sostojanie=0;

But already at the start, the Expert Advisor knows that in the zero state (if(Sostojanie==0){}), it is only allowed to perform operations A, B and C. And depending on what the result of one or more of these operations will be, the EA selects which state to go to (Sostojanie=1;//or 2, or 3 and so on), or vice versa, whether to stay in the current state.

In each state, the Expert Advisor knows what it can and cannot do, and under what conditions it must switch to another state.

 

It was mentioned earlier that the broker can close+re-open an existing order and some of its parameters will change (comments etc).

- I would like to know which parameters will be 100% inherited?(opening time, lots, ...?)

 
chief2000 >>:

Ранее упоминалось что брокер может закрыть+переоткрыть существующий ордер и при этом некоторые его параметры изменятся (комментарии и т.д.).

- Хотелось бы узнать какие параметры на 100% будут унаследованы? (время открытия/закрытия, лоты, ...?)

No one is allowed to touch the lot and the magik, and there will be a broker's addendum to the comment on the tail. But your comment can always be found by searching for a substring.
Reason: