Escalpelamento Confortável.
Introdução.
Este artigo descreve um algoritmo de abertura comercial que permite tornar o escalpamento mais confortável. No entanto, esse algoritmo também pode ser aplicado em outras abordagens comerciais. Na verdade, o artigo oferece um método para ajudar um comerciante em uma negociação tão rápida.
Geralmente, o escalpelamento é considerado um tipo muito nervoso de negociação. Muito importante aqui é a necessidade de indicar os níveis de lote, TakeProfit e StopLoss a cada vez, sendo assim distraído de um gráfico.
Este artigo é a continuação da "Modelagem de apostas como meio de desenvolver a" intuição de mercado "". Eu recomendo lê-lo antes de começar a estudar o presente artigo.
Gostaria de lembrar o que é escalpelamento. Escalpelamento é um método de negociação rápida. Normalmente, em tal lucro comercial é fixado em 1-10 pips (pontos). Escalpelamento é conhecido por sua complexidade, nervosismo e maior atenção necessária. Alguém acha que não é sério, alguém considera isso um domínio perfeito. Quanto a mim, não vou estimar esse tipo de negociação - ela é amplamente discutida e todos têm a própria opinião.
Provavelmente, todo comerciante já tentou usar uma estratégia de escalpelamento. Para alguns comerciantes, o escalpelamento é o tipo mais conveniente de negociação, para outros - pelo contrário. Alguns consideram escalpelamento da negociação mais interessante, outros - uma mera perda de tempo. No entanto, todos podem notar sobre a necessidade de uma maior atenção ao mercado e abrir negócios neste tipo de negociação.
Muitos comerciantes recusam o uso de escalpelamento apenas porque requer muito esforço e nervosismo. No entanto, existe um método para ajudar um escalpador.
Suponha que um comerciante use escalpelamento com um lote fixo e obtenha lucro em cada negócio. Obviamente, é razoável eliminar a necessidade de indicar esses parâmetros todas as vezes para cada negociação. Porque leva tempo extra e chama a atenção de um comerciante de um gráfico.
Isso significa que precisamos de uma ferramenta que abra uma negociação com um lote fixo e níveis TP / SL no comando de um trader. A operação da ferramenta deve ser maximamente simples; além disso, deve minimamente distrair um comerciante de um gráfico.
Tal ferramenta pode ser facilmente implementada usando meios MQL4.
Implementação.
Como base tomaremos um jogo descrito no artigo "Modelagem de Apostas como Meios de Desenvolvimento da" Intuição do Mercado "". Vamos criar uma ferramenta que ajudará a jogar este jogo e a negociar ao mesmo tempo.
Breve descrição do jogo. Duas setas são desenhadas no gráfico - para cima e para baixo. Um comerciante apaga uma flecha desnecessária, fazendo assim uma escolha que denota sua opinião - se um título vai subir ou cair. No início de um novo candelabro, o EA verifica se a previsão de um profissional está certa ou errada. A exatidão da previsão influencia a pontuação do jogo. Além disso, um comerciante pode fazer a sua escolha dentro de um período de tempo limitado, que pode ser alterado (um comerciante decide se deve defini-lo ou não).
Para a implementação, desenharemos mais duas setas uma barra atrás da atual. A barra atual ainda será usada para as apostas. A exclusão de uma seta na barra anterior será um sinal para o EA abrir uma negociação na direção necessária. Além disso, a limitação do período de tempo para a escolha de uma direção comercial será desativada para negociação. Haverá os seguintes parâmetros variáveis: níveis TakeProfit e StopLoss, lote, escorregamento aceitável e o número mágico. Além disso, a negociação pode ser desativada usando a variável bool externa, portanto, o EA será usado apenas para apostas.
Além disso, na abertura comercial, uma seta chamada 'comprar' ou 'vender' será desenhada em um gráfico, dependendo de uma negociação aberta no momento. Isso será feito para impedir que o EA abra novos negócios nesse candlestick. Essa seta será desenhada a 300 pontos do preço de abertura de um bar, então o usuário provavelmente nem notará isso.
A própria EA será dividida em dois blocos - o jogo e a abertura comercial. Assim, um leitor pode ver o que é adicionado ao código.
Então, temos o seguinte código de programa:
O código inclui todos os comentários necessários.
Depois que o Expert Advisor estiver anexado a um gráfico, obteremos o seguinte:
Aqui as últimas duas setas são destinadas ao jogo, as duas flechas antes delas são usadas para abrir ordens.
A exclusão de uma seta no castiçal anterior causará a execução da função OrderSend () e um pedido correspondente será aberto:
Aqui está a guia de alteração dos parâmetros de entrada:
A variável "gap" é responsável pelo número de pontos igual à distância entre uma seta e o preço de abertura de um castiçal. A variável "Negociação" denota a função de negociação, "TP" - TakeProfit em pontos, "SL" - StopLoss em pontos. A variável "Lots" é responsável pelo volume de posições abertas; "slippage" denota o escorregamento admissível em pontos que estamos prontos para aceitar. "MagicNumber" indica o número mágico que é atribuído pelo EA às posições abertas (necessário para que o EA possa rastrear seus "próprios" pedidos). A variável de limite "time_limit" define o número de segundos em que um usuário deve fazer sua escolha. Se "0" é indicado, o tempo não é limitado, isto é, a escolha pode ser feita durante todo o período de formação da vela.
Conclusão.
Como resultado, temos uma garantia para uma negociação confortável usando ordens com parâmetros padrão (TP, SL, Slippage, lote). Esta ferramenta pode ser útil em qualquer negociação. No entanto, é o mais eficientemente usado quando um grande número de negócios é aberto em um curto período de tempo. Por exemplo, no escalpelamento.
Usando este programa, um comerciante não precisa definir os parâmetros de um pedido aberto a cada vez. Assim, o máximo de sua atenção está concentrado em um gráfico. Sem dúvida, isso pode ajudar a aumentar a eficácia da negociação.
Traduzido do russo por MetaQuotes Software Corp.
Estratégia de negociação Mq4
1 - Как правило, первый же вариант оказывается правильным и принимается Заказчиком, 2 - Со второго, так как всегда остаются какие-то мелочи / пожелания Заказчика, 3 - Приходится делать не менее 3-х итераций, прежде чем Заказчик примет работу, 4- 6 - Ir para o conteúdo final da sua busca.
Машинное обучение в трейдинге: теория и практика (торговля и не только)
Добрый день всем, & # 160; Юнаю, что есть на форуме энтузиасты aprendizado de máquina и статистики. Предлагаю в этой теме обсуждать (без холиваров), делиться и обогащать собственную копилку знаний в этой интересной сфере. & # 160; De acordo com as regras de uso do contrato, & ndash; & ndash; & # 160;
ФОРТС. Вопросы по исполнению.
Добрый день, Ренат! Em outras palavras, o & quot; РОРТС большие задержки при выставлении приказов & quot; Вы утверждали, что никаких дополнительных задержек со стороны Вашего сервера не существует и рекомендовали установить машину поближе к Вашему серверу. С большими проблемами удалось это сделать (начальник отдела по.
Отключение WebMoney.
Все получили такое сообщение? Prezado membro da MQL5munity, Por razões técnicas, o sistema de pagamentos do WebMoney em breve será desativado e não estará mais disponível para operações de retirada. Por favor, escolha outro sistema de pagamento adequado do seu perfil. Pedimos desculpas por qualquer inconveniente e.
Интересное и Юмор.
Форумяне, не забывайте соблюдать правила & # 160;
МТ4 или МТ5. Какие преимущества и недостатки?
Особенности языка mql5, тонкости и приёмы работы.
Ванной теме будут обсуждаться недокументированные приёмы работы с языком mql5, примеры решения тех, или иных задач. FAQотелось бы, чтобы эта ветка была по содержанию ближе к FAQ, чем к обсуждению. Предлагаю всем опытным программистам делиться найденными решениями и приёмами программирования.
Антивирус ловит МТ5.
Здравствуйте! подскажите пожалуйста Это только у меня срабатывает антивирус при запуске терминала или так должно быть, или с этим всё же надо что-то делать?
Скорить оптимизацию по всем тикам em 100 раз.
Тестирование советников по всем тикам занимает очень много времени (до завершения теста 5000 часов), & # 160; тем более если при тестировании ведётся поиск сразу ïî множеству параметров в диапазоне с маленьким шагом (старт 0 / шаг 1 / стоп 100) Можно ускорить процесс тестирования за счёт сброса не нужных.
Статьи по торговле на финансовых рынках.
ZUP - зигзаг универсальный с паттернами Песавенто. Поиск паттернов.
Индикаторная платформа ZUP позволяет производить поиск множества известных паттернов, параметры которых уже заданы. Но можно также и подстраивать эти параметры в соответствии со своими требованиями. Есть и возможность создавать новые паттерны с помощью графического интерфейса ZUP и сохранять их параметры в файл. После этого можно быстро проверить, встречаются ли новые паттерны на графиках.
LifeHack para o fim de semana: ForEach на дефайнах (#define)
Промежуточная ступенька для тех, кто всё ещё пишет на MQL4, но никак не может перейти на MQL5. Мы продолжаем искать возможности для написания кода в стиле MQL4. На этот раз рассмотрим макроподстановку препроцессора - #define.
Глубокие нейросети (Vасть V). Байесовская оптимизация гиперпараметров DNN.
В статье рассатриваются возможности байесовской оптимизации гиперпараметров глубоких нейросетей, полученных различными вариантами обучения. Сравнивается качество классификации DNN оптимальными гиперпараметрами при различных вариантах обучения. - орвард-тестами проверена глубина эффективности оптимальных гиперпараметров DNN. Определены возможные направления улучшения качества классификации.
LifeHack para o jogo: готовим фастфуд из индикаторов.
Если вы переходите на MQL5 только сейчас, то эта статья вам пригодится: с одной стороны, доступ к данным индикаторов и к сериям выполнен в привычном вам MQL4-стиле, с другой - вся реализация этой простоты написана на MQL5. Все функции максимально понятны и отлично подходят для пошаговой отладки.
Автоматическое построение линий поддержки и сопротивления.
В статье рассаатривается автоматическое построение линий поддержки и сопротивления через локальные максимумы и минимумы ценовых графиков. Для определения этих экстремумов применяется всем известный индикатор ZigZag.
Правление капиталом по Винсу. Реализация в виде модуля Мастера MQL5.
Статья написана на основе книги Р. Винса & quot; Математика управления капиталом & quot ;. В ней рассматриваются эмпирические и параметрические методы нахождения оптимального размера торгового лота, на основе которых написаны торговые модули управления капиталом для мастера MLQ5.
Тестирование паттернов, возникающих при торговле корзинами валютных пар. IIIасть III.
Мы заканчиваем тестирование паттернов, которые можно увидеть при торговле корзинами пар. В статье представлены результаты тестирования паттернов, отслеживающих движение валют пары по отношению друг к другу.
Паттерн прорыва канала.
Как известно, ценовые тренды образуют ценовые каналы. Один из сильных сигналов на изменение тренда - прорыв текущего канала. В этой статье я предлагаю попробовать автоматизировать процесс поиска таких сигналов и посмотреть, действительно ли можно на этом построить свою стратегию торговли.
Пользовательский тестер стратегий на основе быстрых математических вычислений.
Статья описывает создание пользовательского тестера стратегий и своего собственного анализатора прогонов оптимизации. Прочитав ее, вы поймете, как работает режим математических вычислений и механизм так называемых фреймов, как можно подготовить и загрузить свои собственные данные для расчетов и использовать эффективные алгоритмы их сжатия. Также эта статья будет интереснавсем, кто интересуется способами хранения пользовательской информации внутри эксперта.
Como você pode ver o artigo.
Торговля на финансовых рынках связана с целым комплексом рисков, которые должны учитываться в алгоритмах торговых систем. Снижение таких рисков - важнейшая задача для получения прибыли при трейдинге.
Работа Фрилансерам.
Нужна консультация математика. Расчет критериев для построения кривых. Только для профи.
Необходима консультация по построению кривых. Определение критериев и расчет параметров. Код пишу сам. Использую ALGLIB и похожие библиотеки. От вас - хорошее знание высшей математики, мат. статистики. Опыт применения пакетов MathCad e R будет плюсом. Оплата через этот сервис. Однако общение по.
Очу видеть прошлые важные экономич. отчеты с сайта investir (3 головы - NFP, PMI, CPI) на графике внизу в мт4.
Идея: загрузить все новости разной важности (1-3 башки с сайта investir например), чтобы увидеть как инструмент реагирует на негативные \ позитивные новости (показать "esperado" и "real" - ожидаемые и реальные цифры) Для удобства чтобы эти новости отображались сразу на всем протяженииграфика. Например.
Нужен индикатор & quot; поглощения & quot;
Смысл в том, что нужен индикатор, указывающий, что текущая свеча перекрыла своим телом тело предыдущей свечи. Необходимо, чтобы уведомления могли приходить как PUSH на телефон с установленным mt4. Пример уведомлений "EURUSD call / put" - в зависимости поглотила.
Нужен волновой индикатор на основе двух скользящих средних.
Всем привет. Нужен волновой индикатор на основе двух скользящих средних. Настройки: ТФ по которому проводятся все вычисления. МА1: Период. Тип сглаживания..вет. Толщина. МА2: Период. Тип сглаживания.
Сделать из обычного графика - секундный график.
Необходимо сделать скрипт / программу - которая преобразует обычный график - в секундный график. График можно настроить ïî секундам от 1 до 60 секунд (отоброжение в свечах) Необходимо что бы на график можно было наложить индикаторы и торгового робота. В настройках графика необходимо ввести параметр.
Нужен советник по стратегии на основе 4-х индикаторов.
Написать советника по нескольким индикаторам, с некоторыми дополнительными условиями. Необходима возможность для модернизации. Индикаторы видны на фото. Настройки советника: Стоп лосс Тейк профитМэджик Трейлинг Выставление сетки по мартингейлу Более подробно в техническом задании в.
Нужна библиотека MT4 для отправки команд на binário.
В бублиотеке нужна одна функция открытия ордера (купить / продать опцион) возвращающая результат операции успешно или нет. О о о о о m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m mql5 / de / market / product / 21025 Скорее всего там даже библиотеки есть грузятся на автомате.
Нужен скрипт для открытия ордеров в тестере MT4.
Нужен именно скрипт, ане эксперт для открытия всех типов ордеров в тестере MT4. При запуске должен выводить окно с настройками - тип ордера, sl, tp, lotes, открывать ордер в тестере и выгружаться. Должен быть написан без использования подключенных библиотек (как минимум без использования функций.
Нужна программа для платформы mt5.
нужна отделная программа ну более конкретно панель на которой показыжались те сделки от мт5 каторые уже в плюсе ..ну например у меня 10 шетв и я ьочу однавременно на одной отдельной окошке увидеть все плюсы всех етих шетов. por exemplo 0,001 лота + 2доллара и крестик штоб.
Торговый робот na JFOREX!
1 Работа робота только в определенный промежуток времени, запрет на открытие позиций если время не входит в установленный интервал, закрытие всех открытых позиций в 23:00 по пятницам. 2 Поиск 4х точек (наглядно на скрине) 3 При выполнении определенных условий поиск точки №5 и выставление.
Магазин Приложений.
Gráficos Sincronizados.
Скрипт Synchronized Charts различных самилных различных периодов одного символа различных символов или баров различных периодов одного символа. Запустите скрипт на графике и изменяйте положение и масштаб графика, позиция в истории всех открытых графиков будет синхронизирована. Бары на разных графиках выравниваются по левой границе окна в соответствии с временем открытия.
CreateGridOrdersTune.
Скрипт для открытия сетки ордеров Если Вам необходимо быстро открыть несколько отложенных ордеров (Buy Limit, vender, comprar Stop, Sell Stop) на некотором расстоянии от текущей цены, то этот скрипт избавит Вас от рутинных действий! Разрешите авто-торговлю перед запуском скрипта. Использование: апустите скрипт на графике. Входные параметры: Linguagem das mensagens exibidas (EN, RU, DE, FR, ES) - язык вывода сообщений (английский, русский, немецкий, французский, испанский). Preço para aberto.
AccountQuickReport.
Скрипт создает в отдельном окне краткий торговый отчет. Отчет можно создавать как для всех совершенных сделок, так и для сделок по отдельным финансовым инструментам. Есть возможность задавать временной интервал расчета, записать отчет в htm-файл. Входные параметры скрипта relatório data de início - начальная дата составления отчета. data final do relatório - конечная дата составления отчета. selecção de símbolos para relatório - вариант выбора инструмента составления отчета. allSymbol - отчет сост.
Trade Copier Pro MT5 ilimitado.
O Unlimited Trade Copier Pro é uma aplicação que permite que você trabalhe de forma simples e fácil. То идеальное решение для провайдеров сигналов, которые хотят поделиться своей торговлей с другими трейдерами по всему миру. Один поставщик может копировать сделки на неограниченное количество счетов-получателей, а один получатель также может копировать сделки неограниченного количества провайдеров. Поставщик может указать срока.
Pedido de parada virtual pendente de compra.
Скрипт используется для автоматизации выставления отложенных Comprar Parar ордеров, стоп-лоссов и тейк-профитов на заданных трейдером уровнях. Основные цели Избежать необоснованного входа в длинную позицию на ложном пробое уровня в результате расширения спреда дилинговым центром; Избежать необоснованного срабатывания стоп-лосса в результате & quot; прокола & quot; котировкой важного уровня (фрактала) без подтверждения закрытием цены; Установить нужный виртуальный ордер и войти в рынок при запрете дилин.
Belkaglazer.
Belkaglazer - полностью автоматизированный советник для создания разнообразных торговых стратегий. Você está relacionado com 3-хобобщенных моделях: PriceChannel, Pivot, PriceAction. Модели имеют прозрачную логику. Советник имеет модульную структуру; Модели могут быть использованы в сочетании со следующими стратегиями: breakout, momentum или reversão à média; Советник предоставляет возможности для творчества и исследований; Поддерживает Limit / Stop и Market ордера. Com Instant и Mark.
Herói Grid - полностью автоматизированный советник с использованием продвинутого сеточного алгоритма (P. A.M. A.) вместе с фирменным комплексом торговли ïî ценовому действию (Ação Preço) и модуля самонастраивающейся обработки искусственного инстинкта. Herói da grade разрабатывался, тестировался e оптимизировалсястрогоследуяметодикеразработки & quot; Обратной выборки & quot ;, основанной на & quot; Внутривыборочной & quot; фазе (с. 2012 года в 2017 год) и & quot; Вневыборочной & quot; фазе (с 2004 a partir de 2011). Он прошел тестирование на р.
Tendência PipFinite PRO.
Стратегия пробоя для торговли по тренду, фильтрация и все необходимые функции, встроенные в один мощный инструмент! Trendникальный алгоритм индикатора O Trend Pro oferece uma solução para os problemas que você pode encontrar em sua vida. Новые функции улучшают правила статистических расчетов и улучшают работу индикатора. Você está aqui: Nome de produto: Trend Pro Descrição do item: mql5 / pt / blogs / post / 713938 Mostrar mais em: демо-версию и и и и и и и и и о отеле на отеля.
Avançado Scalper.
Advanced Scalper - Faça o seu download agora mesmo! 15-летнего изучения рынков и программирования торговых советников. Ксперт использует продвинутые алгоритмы выхода и имеет встроенные фильтры спреда и алгоритмы контроля проскальзывания. Гибкая кастомизация в соответствиисс потребностями клиента, широкие возможности настройки. Конечно, есть также рекомендуемые настройки, которые можно посмотреть на странице комментариев. Базовая логика советника уже более двух лет с успехом работает на реальных счетах.
Ação de preço do Apogeu.
Apogeum Price Action - Ação de preço de Apogeu - это полностью автоматизированный торговый советник, который имеет собственный алгоритм распознавания поведения цены и зарождения тренда. Система не использует токсичные методы торговли такие, как мартингейл, усреднения убыточных позиций, не является скальпирующей (уровень прибыли для каждой сделки среднесрочный), а так же обладает фиксированными значениями Stop Loss и Take Profit. Apogeum Price Ação является инвестиционной стратегией, рассчитанной на долгосрочное испол.
Guia Avançado Para MetaTrader 4 - Teste de Estratégia e Otimização.
MT4 enables traders to test Expert Advisors prior to using them in a live market. This allows traders to evaluate the Expert's efficiency and to confirm that it operates as expected.
MT4's " Tester " is a multifunctional window where traders can test trading strategies (objective rules for trade entry, exit and management) and also optimize an Expert's parameters to find the combination of variables that will produce the most favorable results. To open the Tester window:
Any of these actions will open the Tester window at the bottom of the MT4 screen, as shown in Figure 21.
Initially, only the Settings and Journal tabs are seen in the Tester window. The other tabs will appear as certain actions are taken; for example, the Results tab appears only after an Expert has been tested. The Tester window tabs include:
Settings - the settings of the testing and optimization; for example, the time period to be tested. Results - the results of the trade operations performed on historical data by the Expert. Graph - a graphical display of the results. Report - a detailed testing report. Journal - a log where all actions and internal messages of the Expert are recorded. Optimization Results - data regarding every optimization pass, including inputs, profitability and drawdowns. Optimization Graph - the results of the optimization shown in graph form.
Setting up Testing Parameters.
To test an Expert Advisor, click on the Settings tab in the Tester window. Here, the trader will have to select the:
Expert Advisor - Only compiled Expert Advisors will be available for testing, and these will appear in the drop-down menu next to "Expert Advisor." Expert Properties - Once the Expert has been selected, click on the "Expert properties" button to select parameters for each of the three tabs: Testing, Inputs, and Optimization. Symbol and Period - The symbol is defined in the Symbol field; the timeframe is specified in the "Period" field. If there is no historical data saved for the symbol or period, the Tester will automatically download the last 512 historical bars. Model - One of three methods of historical data modeling can be chosen for testing:
o Open prices only - the fastest method suitable for Expert Advisors that control bar opening.
o Control points - results are considered estimates only.
o Every tick - the most accurate method of modeling. Since this method involves a large amount of tick data, it is typically slow and can bog down the computer's operation.
Use Date - The historical price data on which the test will be applied; complete the From and To fields to identify a range. Optimization - Check to enable the Expert parameters optimization mode; if it is disabled, the Expert will be tested but not optimized when the "Start" button is pressed. Open Chart - Opens a new price chart with the symbol selected for testing. The chart will show trade entries and exits, and can be opened only after the Expert has been tested. Modify Expert - Click this to open the MetaEditor and make changes to the code, if desired. Start - Press the "Start" button to being testing or optimization. A progress bar will appear at the bottom of the Tester window, as shown in Figure 22.
MT4 can automatically create consecutive passes of the same Expert, with different inputs on the same data. Performing this optimization can help traders determine the inputs that have the most favorable results. To set up an optimization, traders must specify which variables will be optimized by clicking on the "Expert properties" button in the Tester window. This opens a new window with three tabs, as shown in Figure 23:
Testing - general optimization parameters Inputs - inputs are variables that affect the Expert's operation. Check to include inputs in the optimization; leave unchecked to disregard during optimization. If checked, double-click in each field to specify the values for Start (initial value), Step (change interval) and Stop (final value). Optimization - the tab allows traders to apply limitations during optimization. If any of the conditions is met during a separate pass of the optimization process, the optimization will be interrupted. Check to enable a limit condition, such as Profit Maximum and Consecutive Loss.
After making the desired selections, click "OK" to close the window. Be sure the box next to the Optimization field on the Tester window is checked (to enable optimization), and click "Start" to begin the optimization. Optimizations take varying amounts of time depending on the type of data on which the optimization is performed and the complexity of the inputs. In general, multi-variable optimizations - those that test multiple levels of multiple variables - take the longest.
The Optimization Results tab in the Tester window contains a final report of each pass of the optimization. All data are presented in a table with the following fields, shown in Figure 24:
Pass - pass number. Profit - net profit (gross profit minus gross loss). Total Trades - total number of trades generated. Profit Factor - ratio between the total profit and total loss. Values less than one indicate a losing system. Expected Payoff - mathematical expectation of winning. Drawdown $ - maximum drawdown in relation to the initial deposit. Drawdown % - maximum drawdown in terms of percentage. Inputs - dynamic values of inputs during each pass.
Click any header (such as Profit) to sort data by that field. Right-click the Optimization Results and select "Save as Report" to save a copy of the results.
Automated trading and strategy testing/optimization are advanced features of the MetaTrader 4 platform. Automated trading is popular because it removes some of the emotion from trading, helps traders avoid costly order-entry mistakes, and responds quickly to changing market conditions. The ability to test and optimize a trading idea (Expert Advisor) prior to placing it in a live market with real money is an invaluable step in the development of a profitable trading system.
[Explore Investopedia's top forex broker reviews and find a broker that matches your needs.]
Forex Trading Strategy:
The Ultimate Guide (2018 Update)
Most new traders think that the more complex a strategy is, the more profitable it will be.
Trading Forex using price action is simple, stress free, and highly effective.
In this guide I will share my simple Forex trading strategy with you.
While my Forex Trading Strategy is simple, do not let that simplicity fool you, it is very powerful strategy!
Chapter 1.
Forex Price Action Strategy.
Chapter 3.
Price Action Setups.
Chapter 6.
My Price Action Trading Strategy.
My Forex trading strategy is based completely on price action, no indicators, no confusing techniques, just pure price action!
O que é negociação de ação de preço?
All price movement in Forex comes from bulls (buyers) and bears (sellers). When GBPUSD moves up it’s because there are more bulls than bears and vice versa.
The Forex market (and any market for that matter) is in a constant state of struggle between bulls and bears.
Price action trading is about analysing who currently controls price, bulls or bears and if they are likely to stay in control.
If your analysis shows that bulls are in control and that they are likely to stay in control, then you can buy (long).
If it shows that bears are in control and that they are likely to stay in control, then you can sell (short).
How do you analyse who’s in control of price?
By using two simple price action techniques.
Support and Resistance Areas.
These are buy and sell areas you can easily identify and place on your chart. Once price hits these areas you know it is likely to stall or reverse completely.
This allows you to buy or sell at the right time.
Advanced candlestick analysis.
This is not that basic doji equals reversal stuff you may have seen elsewhere. Advanced candlestick analysis goes much deeper than that so that you have a full understanding of what a chart is telling you.
Once you understand this, one glance at a chart will tell you who’s in control of price (bulls or bears) and if you should buy or sell.
These two techniques make up the core of my price action trading strategy. In fact, those are the only techniques I use to find and trade high probability setups.
My trading strategy differs from most courses you will come across as it is based entirely on Price Action…
It’s simply about reading price and making smart trading decisions.
Forex Price Action Strategy.
My Forex price action strategy was born in 2005 and has been constantly improved over the last 12 years – this strategy has seen it all.
It has survived major market changes from the financial crisis in 2008 to the Swiss Franc disaster in 2014, to Brexit in 2016. It really has seen it all.
My price action strategy works in all market conditions .
From trending markets to low volatility, to ranging, to high volatility, it has weathered it all with consistent profits.
Indicator based strategies work well in specific market conditions. If you have a strategy that works in low volatility markets, it will fail in high volatility, ranging, or trending market conditions.
Price action adapts, indicators don’t!
Price action doesn’t only adapt to changing market conditions though, it adapts to different pairs, different time frames and, crucially, to different traders.
Above all, Price Action keeps your trading simple .
In fact, my Forex trading strategy is so simple that you can trade it from your smartphone. I use this strategy to trade on the go – as of 2017 I take over 70% of my trades from my smartphone.
Keep It Simple.
My Forex trading strategy was created with simplicity in mind. The most common downfall of today’s traders is over complicating their strategy.
We have all seen charts that look like this.
How can you trade comfortably using a chart like this?
How can you trade efficiently using a chart like this?
How can you trade from your smartphone using a chart like this?
You can’t, it is too messy.
The core rule of my price action strategy is to keep trading simple. Because the Forex trading strategies that work best are simple .
The only thing I place on my charts is support and resistance areas . I use these support and resistance areas in conjunction with candlestick analysis to trade Forex.
So what does a clean Forex chart look like? Much better than the monstrosity above!
This chart is uncluttered, easy to understand and to navigate, with nothing to distract you from analysing price action.
This style of trading is quick, efficient, stress-free, and you can do it from anywhere, including your smartphone.
So if you want a simple Forex strategy, keep reading.
Support & Resistance Areas.
Support and resistance areas show you where to buy and sell, they are a vital part of every traders toolkit, and it is essential that you learn how to place them .
What is Support and Resistance?
Placing support and resistance areas is the most important skill you can master in trading.
And placing them is easy.
Support and resistance areas divide your chart up into buy and sell areas. An area that sits above current price is a sell area, any area below current price is a buy area.
Support = Buy Area.
The terms buyers and bulls are interchangeable. Support is a buy area as buyers are found at support.
Resistance = Sell Area.
The terms sellers and bears are interchangeable. Resistance is a sell area as sellers are found at resistance.
On the GBPUSD chart below, you can see price is approaching the blue shaded area at 1.3500. This is a strong resistance (sell) area.
When price approaches a sell area large amounts of sell orders are triggered countering buy orders. This usually results in price stalling or even turning around completely for a reversal.
Why does this happen though?
It’s simple, the market movers like banks and hedge funds place their orders at areas of support and resistance.
Why Do Market Movers Place Their Orders At SR?
Good traders don’t randomly place entry orders and hope that they get lucky. They place their entry orders at significant price levels. Significant levels come in many forms.
Yearly, monthly, weekly highs or lows. Rounded numbers such at 1.0000 and 1.0500 (also called psychological levels) All time highs or lows. Areas in which price has stalled or reversed more than once.
In the GBPUSD chart example above, we can see that price has stalled at the 1.3070 twice (green highlights). The next time it approaches the level it pulls back again and then again two more times (yellow highlights).
Because market movers place their buy orders at the 1.3070 and when price hits the area the buys trigger causing a reversal.
This happens all the time on every Forex pair and in every financial market for that matter.
This is how markets work, buy and sell orders are grouped together in the same general area and when they are hit we see the impact on price.
Placing Support and Resistance Areas.
There are a lot of indicators out there that claim to give you great support and resistance areas.
I have tried them all and I do not find them reliable.
Support and resistance placements still need to be done by a person. These are my support and resistance areas, but if you want to trade more pairs you will need to place them yourself.
A good Forex trading strategy requires some work!
But don’t worry, it is easy, all you are doing is placing horizontal lines when you spot an area with two or more bounces.
I am going to break it down into a step by step process for you though. But first, we need to define some rules for support and resistance areas.
Three Rules to Support and Resistance.
There are three key rules you need to keep in mind when placing support and resistance areas.
Place areas on the body of a candle, the body is more important than the wick. The more recent the bounce the more important. Prioritise recent bounces over older bounces. You need at least two connecting bounces to place a support and resistance area. There are a few exceptions to this, the most common one being for points which are yearly or all-time highs/lows. When you spot a year or all-time high/low you can place an area there even if it has only once bounce.
Step By Step Guide to Placing Support and Resistance.
Step 1: Select a daily chart and zoom out until you see around one year of data. Don’t worry if you see a little more or less than one year, it’s not a big deal.
You will generally find that there are 5-8 support and resistance areas on most charts. If you have more than 8 you probably placed too many.
Advanced Candlestick Analysis.
Most new traders learn a little bit about candlestick analysis.
But most of what they learn is completely useless!
Well the standard approach to candlestick analysis is basic pattern recognition, which fails to work in real trading.
I delve much deeper than that, I look at the story behind the candle and in this chapter I will show you how to do that too.
You can’t skip straight to advanced candlestick analysis without knowing some basics first. If you don’t know the basics, that’s fine, I got you covered!
The Truth About Candlestick Analysis.
When Forex traders first start out they usually learn about candlesticks.
But what they learn is usually useless.
They normally see a list of “candle patterns” like the one below. Each pattern has a set in stone definition and that is the only meaning it can have.
This is not candlestick analysis, it is pattern recognition.
And for a price action trader, it is useless.
Actually, it is worse than useless. Thinking about candles as just patterns is counterproductive. It makes you a worse trader, it leads you to make massive mistakes.
Giving a pattern a set definition leads to tunnel vision. When you see that specific pattern, you assume that something will happen.
But that is not how candlesticks work.
All candlesticks need to be assessed based on the candlesticks around them, and many other factors.
Below is a candlestick pattern commonly called a “spinning top”.
Normally people say that a spinning top means a reversal is imminent, which can be true. However, this same pattern can also mean that a continuation is imminent. It can mean that price is temporarily stalling.
It can mean a lot of different things.
Thinking of candles as simple patterns is the wrong way to do things.
You need to look beyond the pattern and read the story of price.
The Story of Price.
Every single candle on your chart is telling you a story. When you combine those candles together, you get the story of price.
The foundation of my Forex trading strategy is reading and understanding the story of price.
Reading and understanding the story of price is vital in Forex. It is vital because it allows you to answer one of the most important questions in trading…
Who is in control of price?
This question has three possible answers: buyers, sellers, or neither.
Being able to accurately answer this question is vital. If you are about to enter a short trade and you ask yourself.
“Who is in control of price?” and your answer is “buyers”, well perhaps selling is not a great idea.
Let’s break down the story of price.
If you look at the three highlighted candles below, it is easy to conclude that sellers are in control of price.
The candles all closed lower than they opened, they all created new lows beyond the previous candles low and they all had small upper wicks in comparison to the candle body. The small upper wicks indicate that buyers were unable to push price up by much.
But what does the highlighted candle in the next chart tell us?
It has a short upper wick, a small body, and a long lower wick. This is what I call an indecision candle.
What’s an Indecision Candle?
Indecision candles occur when neither buyers or sellers can gain and maintain control of price. They are common, but if used in the right way, they can be very powerful.
Take a look at this bullish trend (yellow highlight), it is a strong trend, there are several bullish candles heading towards an area of resistance. The big bullish candles tell us that during the highlighted period buyers were in complete control of price.
When price hits resistance we get an indecision candle forming (green highlight).
Let’s break this candle down into a story so you understand why it indicates indecision.
Large Upper Wick (Blue Highlight)
A large upper wick shows that buyers tried to continue the bullish trend but failed. Sellers took control of price and pushed it down.
Small Bearish Body (Green Highlight)
The small bearish body shows that sellers were able to close lower than the open. This is significant because in the three candles before this price consistently closed higher than open. This shows us that buyers are losing power.
Small Lower Wick (Red Highlight)
The small lower wick shows us that sellers were not able to gain much ground either. This tells us that sellers are not strong enough to turn price around completely. However, they are strong enough to stall further buyer movement.
All together this indecision candle forming right after strong bullish candles suggests that power has shifted from a decidedly bullish (buyer) market to an undecided market. While sellers are not in control, neither are buyers.
But there is one more thing we need to look at…
… The indecision candle is forming on top of a resistance area. Let’s looks at this chart again.
If you remember, in the previous chapter we talked about resistance being a sell area and support being a buy area.
So the image above shows us three strong bullish candles heading into a resistance area. And then…
Price stalls and we get indecision forming on top of that area.
This tells us that the sell area is working. When price pushed into that area sell orders triggered and buyers could no longer continue up.
That is the story of price for this chart.
And this story gives us a nice little price action trade setup.
Setups With My Forex Trading Strategy.
Price action allows you to take many different types of trades, reversals, continuations, range, swing, breakout and scalp trades to name a few.
In my free Forex trading strategy I will focus on one type of setup, the easiest to spot and trade, reversal .
How to Spot a Reversal Trade.
Reversals occur quite often, but if you do not know what to look for, you cannot trade them.
Reversals are one of the strongest price action setups, and one of the easiest to trade. And because they occur so often, you can trade this setup exclusively and be a profitable trader.
In fact, for years Forex trading strategy focussed on reversals only. However, these days I trade more price action setups.
Reversal trades come in three parts:
The preceding trend. The Indecision candle(s). The reversal trend.
Let’s break down each of these parts.
The Preceding Trend.
A preceding trend is a strong move by the bears/bulls heading into an area of support/resistance.
In the example above, the preceding trend is a very strong bearish move, indicating that there are a lot of bears in the market and very few bulls. If bulls were strong then price would not be trending down.
The preceding trend shows us that bears (sellers) have strong control of price and they are pushing price down into a support area.
The opposite applies for a bullish preceding trend which would show bulls (buyers) trending towards resistance, as you see below.
A preceding trend can be formed by as little as one candle. If the candle is strong and covers a lot of price distance, I categorise it as a preceding trend for the purposes of reversal trading.
The example below shows a single candle preceding tend.
Preceding trends are pretty simple. As long as you see a strong move heading into an area of support or resistance, you can consider it a preceding trend.
The Indecision Candle(s)
A reversal setup will have one to three indecision candles. The indecision candles need to form on or near to the support and resistance area.
If indecision does not form on or near to the area of support and resistance, it is not a valid reversal setup.
Why does it need to be on a support and resistance area?
An indecision candle in a bullish preceding trend indicates that buyers are possibly losing control, and sellers may be gaining control. In a bearish preceding trend it indicates that sellers are losing control and buyers may be gaining control.
However, an indecision candle does not indicate that price will reverse with any degree of certainty.
An indecision candle indicates only one thing…
You cannot take a trade based solely on indecision. The image below shows indecision forming between support and resistance. If you were to enter reversal trades based solely on indecision, it wouldn’t work out too well…
What about when a bullish preceding trend heads into an area of resistance (sell area) or a bearish trend into support (buy area) and indecision forms?
Well, then we get the makings of a high probability reversal setup.
But we cannot enter just yet, we need confirmation, which comes in at part three of a reversal setup.
The Reversal Trend.
The reversal trend is the third and most important part of a reversal setup. This is where we make our profit!
After a preceding trend stalls at support, and indecision forms, you often see a reversal trend. The image below shows a bearish reversal trend forming after indecision on resistance.
In this case we saw a transition of power from a bullish preceding trend to a bearish reversal trend separated by a stall on resistance.
Where do you enter the trade though? Let’s discuss that in the next chapter.
Trading Reversal Trades With My Strategy.
You know what a reversal trade looks like.
You know that you need to enter after indecision and before the reversal trend.
In this chapter I will show you how to use my Forex trading strategy to trade reversals profitably.
Don’t worry, entering reversal trades at the right time is a lot easier than you may think.
My Forex trading strategy was built on reversal trading. It has now expanded beyond just reversals, but reversal trading is where it all started. Over the years I have refined reversal trade entries into a simple step-by-step process.
Entering trades does not need to be difficult – remember, my goal is to keep everything simple.
Getting in at the Right Time.
In the previous chapter I explained that a reversal comes in three parts.
The preceding trend. The Indecision candle(s). The reversal trend.
You need to enter the reversal trade after part two (indecision) closes, but before part three (reversal trend) completely takes off. Obviously if you enter after the reversal trend takes off, it is too late.
You also need to make sure you do not enter too early as you could be entering a false setup.
In the image below you see a preceding trend heading into support, indecision, and a failed reversal trend. If you entered too early, you would have failed this trade.
Failed trades happen, there is nothing you can do about them.
But getting in at the right time lowers your percentage of failed trades.
Many people wait for a candle close to get in, but I have tested this thoroughly and waiting for closes gets you in too late. In the image below you can see the first candle in the reversal trend closing far from support.
This means you miss out on a lot of potential profit, which is obviously not good.
The key to reversal trading, or any trading for that matter is getting in at the right time .
So, how do you do that?
How to Enter Reversal Trade.
I have tested countless entry methods in the last 15 years. In that time I have found three awesome entry strategies: entering on new high/low, retrace entries, and distance entries.
In my free strategy I will teach you the easiest, entering on new highs/lows.
When indecision forms on an area of support or resistance, you can use the high or low of the indecision candle as an entry trigger and as a stop loss.
In the image above indecision has formed on resistance after a bullish preceding trend, so we want to enter a short reversal trade.
We set our entry a few pips below the low of the indecision candle, and our stop loss a few pips above the highest point of the candle.
In trading, highs and lows are very important. If a new low is created from resistance it indicates sellers have taken control of price, which means we want to be short.
Our stop loss sits above the high as a break of that high would indicate buyers have regained control of price.
For long trades you set your entry a few pips above the high of indecision, and a few pips below the low.
This is the most simple form of trade entry, but also one of the most effective.
Now that you know how to enter, you need to know where to set your target.
Where to Set Your Target.
Targets are also very easy, you need to make sure your target comes before major barriers like the next area of support or resistance.
So, if you enter a long reversal from support, make sure that your target is before the next resistance area.
The minimum risk to reward ratio I use is 1:1.5 R. This means that my target has to be a minimum of 1.5 times the size of my stop.
If my stop is 100 pips, the minimum size of my target is 150 pips (1.5 x 100).
If my stop is 75 pips, the minimum size of my target is 112.5 pips (1.5 x 75).
If there is a major barrier like the next support and resistance area in the way of my minimum target I skip the trade.
In the image above the support area is before my minimum target of 1.5 R is met so I skip the trade.
What Pairs and Timeframes With The Forex Trading Strategy?
The last thing you need to know is the pairs and timeframes.
This strategy works on every single Forex pair, and it also works in other markets like cryptocurrencies, options, futures, stocks and everything.
I trade around 10 pairs regularly.
However, I often have extra pairs on my list that I monitor. If you want to see what I am currently watching check out my weekly analysis on YouTube.
As for time frames, I currently trade these.
Many people do not have access to the 6, 8 and 12 hour time frames because their broker doesn’t support it.
The general rule in trading is the more time frames you trade the more trades you find.
If your broker does not support 6, 8 and 12 hour time frames you need to find a broker who does, or simply use a charting platform separate to your broker.
While this strategy can be traded with just the 4 hour and daily time frames, there is absolutely no sense in sacrificing potential trades because your broker is too outdated to provide new time frames.
Learn More About My Forex Trading Strategy.
If you want to get my latest analysis, or want to learn more price action setups, I got you covered.
My Weekly Analysis.
Every Monday I do weekly analysis using my price action strategy. You can check it out on my YouTube channel.
Forex Mastermind.
If you want a more in-depth guide to my Forex trading strategy you can check out Forex Mastermind.
In my course, I expand on this strategy, and I also share different price action strategies.
Learn My Forex Scalping Strategy.
While the strategy above is an awesome day trading strategy and even a swing trading strategy, for scalping you will need a different approach.
Forex Strategies.
Forex trading cannot be consistently profitable without adhering to some Forex strategy. It takes time and effort to build your own trading strategy or to adapt an existing one to your trading needs and style.
What Is a Trading Strategy?
Most frequently, a trading strategy is a set of entry and exit rules , which a trader can use to open and close positions in the foreign exchange market. This rules can be very simple or very complex. Simple strategies usually require only few confirmations, while advanced strategies may require multiple confirmations and signals from different sources.
Additionally, a trading strategy may contain some money management rules or guidelines. Some strategies (e. g. Martingale) can be centered strictly around position sizing techniques.
Apart from the entry/exit rules and optional money management guidelines, strategies are often characterized by the list of trading tools required to employ the given strategy. These tools are usually charts, technical or fundamental indicators, some market data or anything else that can be used in trading. When choosing a strategy, you need to understand, which of the required tools you have in possession.
It is important to choose a strategy or system that is easy to follow with your daily trading schedule and that can be applied successfully with your account balance size.
Mechanical vs. Discretionary.
Forex strategies that are traded based on strict mathematical rules with no ambiguous conditions and no important trading decisions to be made by the trader are called mechanical . A good example of a mechanical system is a moving average cross strategy, where MA periods are given and positions are entered and exited exactly at the point of cross. When working with mechanical trading strategy, it is easy to backtest one and determine its profitability. You can also automate such system via MetaTrader expert advisors or any other trading software. The usual drawback of such strategies is their lack of flexibility before the fundamental changes in the market behavior. Mechanical strategies are a good choice for traders knowledgeable in trading automation and backtesting.
Strategies that retain some uncertainty and cannot be easily formalized into mathematical rules are called discretionary . Such strategies can be backtested only manually. They are also prone to emotional errors and various psychological biases. On the bright side, discretionary trading is very flexible and allows experienced traders to avoid losses in difficult market situation, while offering an opportunity to extend profit when traders deem it feasible. Newbie currency traders should probably stay away from discretionary trading, or at least try to minimize the extent of their discretion in trading.
Strategies.
In this Forex strategy repository, you will find various strategies that are divided into three major categories:
Indicator Forex strategies are such trading strategies that are based on the standard Forex chart indicators and can be used by anyone who has an access to some charting software (e. g. MetaTrader platform). These FX strategies are recommended to traders that prefer technical analysis indicators over everything else:
Price Action.
Price action Forex strategies are the currency trading strategies that do not use any chart or fundamental indicators but instead are based purely on the price action. These strategies will fit both short-term and long-term traders, who do not like the delay of the standard indicators and prefer to listen as the market is speaking. Various candlestick patterns, waves, tick-based strategies, grid and pending position systems — they all fall into this category:
Fundamental.
Fundamental Forex strategies are strategies based on purely fundamental factors that stand behind the bought and sold currencies. Various fundamental indicators, such as interest rates and macroeconomic statistics, affect the behavior of the Forex market. These strategies are quite popular and will benefit long-term traders that prefer fundamental data analysis over technical factors:
Testing Your Forex Strategy.
It is very important to test your trading strategy before going live with it. There are two ways to test your potential trading strategy: backtesting and forward testing.
Backtesting.
Backtesting is a kind of a strategy test performed on the past data. It can be either automated or manual. For automated backtesting, a special software should be coded. Automated testing is more precise but requires a fully mechanical trading system to test. Manual testing is slow and can be rather inaccurate, but requires no extra programming and can be done without any special preparation process. Any backtesting results should be taken with a grain of salt as the tested strategy might have been created to fit particular backetsting historical data.
Forward Testing.
Forward testing is performed either on a demo account or on a very small (micro) live account. During such tests, you trade normally with your strategy as if you were trading your live account. As with backtesting, forward testing can also be automated. In this case, you would need to create a trading robot or expert advisor to execute your system. Of course, with discretionary strategy, you are limited solely to manual testing. Forward testing results are considered to be more useful and representative than those of the backtests.
Interpreting the Results.
However you decide to test your strategy, you need to understand the results you get. Intuitively, you would want to judge the results according to strategy's profitability, but you should not forget about other important parameters of successful trading strategies. They are: low drawdown sizes, short drawdown periods, high probability of winning, high average reward-to-risk ratios and big number of trades. Ideally, your system should earn equally well on bullish and bearish trades, the resulting balance curve should be consistent and uniform, without significant drops or long flat periods.
If you are using MetaTrader for backtesting or forward testing, you can use our report analysis tool to better understand the strong and weak sides of your strategy.
Further Reading.
If you want need information on Forex strategies or need some additional examples of working strategies, you are welcome to browse our e-books section on strategies to learn from completely free downloadable e-books. You may also choose to read some articles from our strategy building section to improve your knowledge of the subject.
If you want to share your Forex trading strategy with other traders, or want to ask some questions regarding the strategies presented here, please, join a discussion of the Forex strategies at the forum.
Simple Expert Advisor.
This section dwells on the principles of creating a simple trading Expert Advisor.
Preliminary Arguments.
Before starting to program a trading Expert Advisor, it is necessary to define general principles of a future program. There are no strict program creating rules. However, once having created a program, a programmer usually continues to improve it. To be able to easily understand the program in future, it must be created in accordance with a well-thought and easy-to-understand scheme (it is especially important if a program will be further improved by another programmer). The most convenient program is the one that consists of functional blocks, each of which is responsible for its part of calculations. To create an algorithm of a trading Expert Advisor, let's analyze what an operating program should do.
One of the most important data in the formation of trade orders is the information about orders that already exist in a client terminal. Some of trading strategies allow only one unidirectional order. Generally, if a trading strategy allows, several orders can be open in a terminal at the same time, though their number should be reasonably limited. When using any strategy, trade decisions should be made taking into account the current situation. Before a trade decision is made in a program, it is necessary to know what trading orders have already been opened or placed. First of all a program must contain a block of orders accounting which is among the first to be executed.
During an EA execution trading decisions should be made, the implementation of which leads to the execution of trade operations. Code part responsible for trade orders formation is better written in a separate block. An Expert Advisor can form a trade request to open a new pending or market order, close or modify any of existing orders or perform no actions at all. An EA must also calculate order prices depending on a user's desire.
Trade decisions should be made in a program on the bases of trade criteria. The success of the whole program depends on the correctness of detecting trade criteria in the program. When calculating trade criteria a program can (and must) take into account all information that can be useful. For example, an Expert Advisor can analyze combination of technical indicator values, time of important news releases, current time, values of some price levels, etc. For convenience, the program part responsible for the calculation of trading criteria should be written in a separate block.
A trading Expert Advisor must necessarily contain error processing block. Analyzing errors that may occur in the execution of trade operation allows, on the one side, to repeat a trade request and, on the other hand, to inform a user about a possible conflict situation.
Structure of a Simple Expert Advisor.
Below is a structural scheme of a simple Expert Advisor constructed on the basis of several functional blocks, in each block a certain detached part of calculations.
Fig. 109. Structural scheme of a simple Expert Advisor.
On the following EA development stage there is no program code yet. At the same time the algorithm of a program is to a great extent formed. How the EA built on the bases of the offered scheme will operate can be easily understood simply looking on the scheme and orienting upon block names and relations arrays (control passing) between them.
After program start control is passed to the block of preliminary processing. In this block some general parameters can be analyzed. For example, if there are not enough bars in a window (bars necessary for calculating parameters of technical indicators), an EA will not be able to operate adequately. In such a case an EA must terminate operation preliminarily informing a user about it and reporting about the reason of termination. If there are no contraindicatons of a general character, control is passed to order accounting block.
In the block of accounting orders the number and quality of orders existing in a client terminal for a security (to the window of which the EA is attached) is detected. In this block orders of other securities must be eliminated. If a programmed trading strategy requires using only market orders (and does not use pending orders) the fact of presence of pending orders must be detected. If a strategy admits only one market order and there are actually several orders, this fact should also be known. The task of the order accounting block (in this scheme) is in defining whether the current trading situation corresponds with an expected one, i. e. that in which the EA can adequately operate. If the situation corresponds, control must be passed to the next block to continue the EA's operation; if not, the EA's operation must be terminated and this fact must be reported to a user.
If there are no orders in the terminal or the number and quality of existing orders corresponds to what was expected, control is passed to the block of defining trading criteria. In this block all criteria necessary for making trade decisions are calculated, namely criteria for opening, closing and modifying orders. Further control is passed to the block of closing orders.
It is easy to understand why in the offered scheme the block of closing orders is executed earlier than the block of opening orders. It is always more reasonable to process first existing orders (close or modify) and only after that to open new orders. Generally, it is correct to be guided by the desire to have as little orders as possible. During the execution of this block all orders, for which the closing criterion has been activated, must be closed.
After all necessary orders has been closed, control is passed to a block of new orders size calculation. There are a lot of algorithms for calculating an order volume. The simplest of them is using a constant, fixed lot size. It is convenient to use this algorithm in a program for testing strategies. More popular method of defining an order size is setting the number of lots depending on the amount of free margin, for example 30-40% of it. If free margin is not enough, the program terminates its operation having informed a user about the reason.
After the number of lots for opening new orders is defined, control is passed to order opening block. If any of criteria calculated earlier points to the necessity of opening an order of a certain type, a trade request to open an order is formed in this block.
There is also error analyzing block in an Expert Advisor. If any trade operation failed, control (only in this case) is passed to the error processing block. If an error returned by a server or client terminal is not crucial, one more attempt is made to perform a trade operation. If a crucial error is returned (for example, an account is blocked), an EA must terminate its operation. Remember, in MQL4 there is no possibility of program terminating an EA's operation in a security window (as distinct from scripts, see Special Functions). What can be done in a program way is the termination of start(). At a new start of the function start() on a new tick the value of a certain variable-flag prohibiting trading (in this case enabled as a result of a critical error) can be analyzed and control can be passed for the termination of the special function operation; thus formation of new trade request is not permitted. In the offered scheme the flag value is analyzed in the block of preliminary processing.
Trading Strategy.
Market prices are constantly moving. Market state at any moment of time can be conditionally characterized either as a trend - strong unidirectional price change (rise or fall), or as a flat - lateral price movement with weak deviations from a certain average. These market characteristics are conditional, because there are no clear criteria, according to which trend or flat can be identified. For example, long lateral movements with strong deviations that can be traced neither to a flat nor to a trend. Generally it is assumed that the market is mainly in the state of lateral movement and trends usually take place 15-20% of time.
Fig. 110. Flat and trend in the market.
All trading strategies also can be conventionally divided into two main groups. The first group contains flat-oriented strategies. The main idea of such strategies is that after an evident deviation price must return to the previous position, that's why orders are opened in the direction contrary to the last price movement. The second group strategies are trend strategies, when orders are opened in the same direction as the salt price movement. There are more complicated (combined) strategies. Such strategies take into account many different factors that characterize market; as a result trading can be executed both on flat and trend. It is not hard to implement trading according to this or that strategy technically - MQL4 contains all necessary means for it. The main work in the creation of once own strategy consists in the search of trading criteria.
Trading Criteria.
In this example we will try to construct a trend Expert Advisor, i. e. the one that will open orders in the price movement direction. So, we need to find among various technical indicators those that detect a trend beginning. One of the simplest methods of searching trading criteria is based on the analysis of the combination of MAs with different averaging periods. Fig. 111 and Fig. 112 show the position of two different MA (with periods of averaging 11 and 31) on different market parts. Averages with small averaging period (red lines) are closer to a price chart, twisty and movable. Moving averages with larger period of averaging (blue line) are more inert, have larger lag and are situated farther from market prices. Let's pay attention to places where MAs with different averaging periods cross and try to decide, whether the fact of MA crossing can be used as a reading criterion.
Fig. 111. Crossing of MA(11) and MA(31) when price movement direction changes.
In Fig. 111 we see a market part where opening orders in the direction of price movement at MA crossing is justified. In point A the red line crosses the blue one from bottom upwards, after that the market price continues growing for some time. Further reverse MA crossing indicates the price movement direction change. If we open a Buy order at point A and close it at B, we will get profit proportional to difference of A and B prices.
Fig. 112. Crossing of MA(11) and MA(31) when price movement direction changes.
At the same time there are other moments in the market when MA cross, but this does not lead to further considerable price rise or fall (Fig. 112). Orders opened at MA crossing at such moments will lead to losses. If Sell is opened at A and closed at B, such trading will bring losses. The same can be said about a Buy order opened at B and closed at C.
The success of the whole strategy implemented on the basis of MA crossing depends on the number of parts that can be characterized as trend and flat. In flat often MA crossing is a regular event that interferes with any trend strategy. Numerous false signals as a rule lead to losses. That is why this sign - crossing of MAs with different averaging period - can be used for building trading strategies only in combination with other signs proving a trend. In this example (for constructing a simple Expert Advisor) we will have to refuse using this sign.
We will use another sign. Analyzing visually the character of price changes in the market, we can see that a long one-direction price rise or fall often appears as a result of a short strong movement. In other words, if within a short period a strong movement happened, we may expect its continuation in a medium-term period.
Fig. 113. Strong price movement can lead to a trend development.
Fig. 113 shows the market period when a strong movement resulted in the continuation of the price change in the same direction. As the "a strong movement" we may use the difference of MAs with different averaging periods. The stronger the movement, the larger is the lag of MA with larger averaging period from MA with a small period of averaging. Moreover, even strong discontinuous price movements with further return do not result in a large difference between MAs, i. e. numerous false signals do not appear. For example, price jump by 50 points with further return (in the center in Fig. 113) entailed increase of difference between MAs only by 20 points. At the same time a really strong movement (which is not usually accompanied by a considerable correction) in point A resulted in the difference increase up to 25 - 30 points.
If Buy order is opened when a certain value of difference between MAs is reached, for example in A, most probably the order will be profitable when a price reaches a preset Stop order value. Let's use this value as a trading criterion in our Expert Advisor.
Number of Orders.
In this example we analyze an Expert Advisor that admits presence of only one market order, pending orders are not provided. Such an approach is justified not only in this certain example, but can be used as the basis for any strategy.
Pending orders are usually used when a developer has quite a reliable criterion for forecasting the future price change with high probability. If there is no such criterion, no need to use pending orders.
The situation when several opposite orders for one security are open also cannot be considered reasonable. It was written earlier that from economical point of view opposite orders are considered to be senseless, especially if the order prices are equal (see Closing and Deleting Orders). In such a case we should close one order by another one and wait for a signal to open one market order in a certain direction.
Relation of Trading Criteria.
From this position it becomes clear what relations are possible between trading criteria. Fig. 114 shows three variants of correlation of trading criteria, when each criterion is important (valid). Actions (opening and closing market orders) take place clockwise on the following pictures.
Fig. 114. Order opening and closing criteria correlation (a and b - correct, c - incorrect).
The most popular variant of a correctly formed trading criteria is the variant a . After being opened a market order Buy is held upon till the moment when criterion requiring its closing triggers. After that a pause occurs when no orders are opened. Further a market order Sell can be opened. Conditions for closing a Sell order (in accordance with correctly formed criteria) occur earlier, than conditions for opening a Buy order. However, a Buy order can be opened once again, if a trading criterion requires this. But according to this variant a market order cannot be opened if there is an open market order in the contrary direction.
Similar criteria correlation is in the variant b . The difference is that a criterion for opening any market order is at the same time a criterion for closing the opposite order. This variant like the variant a does not allow several orders opened in the terminal at the same time on one security.
The variant of criteria correlation is incorrect. According to this variant opening of a market order is allowed when contrary orders are not closed yet, which is senseless. There can be rare cases when this variant is partially justified. Opening of an opposite order is sometimes acceptable for compensating losses occurring at small corrections after strong price movements. In such cases an opposite order can be opened of the same or smaller value than the already existing one and then closed when the correction is over. Such a tactic allows not to interfere with the "main" order opened in the trend direction.
In general case several one-direction orders are also possible. This may be justified when an earlier opened order is protected by a Stop order and the criterion pointing at the price development in the same direction triggered once again. However, when creating such a strategy, a developer must be fully aware that in case of a sharp price movement change the placed stop orders may be unexecuted by some brokers at the first price touch. And the loss will be proportionate to the total value of one-directional market orders.
In our example we use variant b of trading criteria correlation. All opened market orders are closed either by a stop order or after a criterion of opening an order in opposite direction triggers (here criterion of closing Buy coincides with that of opening Sell and vice versa).
Size of Opened Orders.
In any trading strategy order sizes should be reasonably limited. In a simple case a fixed order size is used in an Expert Advisor. Before EA operation start, a user can set any size of future orders and leave it unchanged for some time. Further if balance changes, a user can set up a new value of lot numbers of opened orders.
A too small order size provides more confidence in operation at the unpredictable market change, but the profit in case of success will be not so large. If the order size is too large, large profit can be acquired, but such an EA will be too risky. Usually the size of opened orders is set up so, that margin requirements do not exceed 2-35% percent of the balance or free margin (if a strategy allows only one opened order, balance and free margin at the moment before the order opening will be equal).
In this example both variants are implemented. A user may choose either to indicate directly values of orders or set the value in percentage from the free margin.
Programming Details.
A simple trend Expert Advisor tradingexpert. mq4 constructed on the basis of previous arguments can look like this:
Describing Variables.
One more criterion in program estimation is its readability. A program is considered to be correctly written, if it can be easily read by other programmers, that's why all main program parts and main moments characterizing the strategy must be commented. This is also why it is recommended to declare and comment all variables at the beginning of the program.
In the block 1-2 external and global variables are described.
According to rules, external and global variables must be opened before their first usage (see Types of Variables), that's why they are declared in the program head part. All local variables of the function start() are gathered and described in the upper function part (block 2-3) immediately after the function header. Rules of declaring local variables do not require it, but also do not prohibit. If a programmer faces difficulties in understanding the meaning of a variable when reading the program, he can refer to the upper program part and find out the meaning and type of any variable. It is very convenient in programming practice.
Block of preliminary processing.
In this example the preprocessing consists of two parts (block 3-4). The program terminates operation if there are not enough bars in a security window; in such a case it is impossible to detect correctly (in block 5-6) values of moving averages necessary for calculating criteria. Besides here the value of the variable Work is analyzed. In the normal EA operation the variable value is always 'true' (it is set once during initialization). If a critical error occurs in the program operation, 'false' is assigned to this variable and start() finishes its operation. This value will not change in future, that is why the following code is not executed. In such a case the program operation must be stopped and the reason for the critical error must be detected (if needed, a dealing center must be contacted). After the situation is solved, the program can be started once again, i. e. the EA can be attached to a security window.
Accounting orders.
The described Expert Advisor allows working only with one market order. The task of the orders accounting block (block 4-5) is to define characteristics of an opened order, if there is one. In the loop going through orders 'for' all existing market and pending orders are checked, namely from the first (int i=1) to the last one (i<=OrdersTotal()). In each cycle iteration the next order is selected by the function OrderSelect(). The selection is made from a source of opened and pending orders (SELECT_BY_POS).
If the selection is executed successfully (i. e. there is one more order in the terminal), further this order and the situation must be analyzed: whether the order is opened for the security, at which the EA operates, whether the order is market or pending; it also must be taken into account when counting orders. In the line:
all orders opened for another security are eliminated. Operator 'continue' stops the iteration and characteristics of such an order are not processed. But if the order is opened for the security, to the window of which the EA is attached, it is further analyzed.
If OrderType() returns value more than 1 (see Types of Trades), the selected order is a pending one. But in this Expert Advisor managing pending orders is not provided. It means the execution of start() must be terminated, because a conflict situation occurred. In such a case after a message about the operation termination start() execution is stopped by the operator 'return'.
If the last check showed that the analyzed order is a market order, the total number of orders for a security is calculated and analyzed. For the first of such orders all necessary characteristics are defined. If in the next iteration the order counter (variable Total) finds the second market order, the situation is also considered to be conflict, because the EA cannot manage more than one market order. In such a case start() execution is stopped after showing a corresponding message.
As a result of the order accounting block execution (if all checks were successful) the variable Total preserves its zero value if there are no market orders, or gets the value 1 if there is a market order for our security. In the latter case some variables set in correspondence with the order characteristics (number, type, opening price, stop levels and order value) also get their values.
Calculating Trading Criteria.
In the analyzed example definition of trading criteria (block 5-6) is calculated on the bases of difference between Moving Averages with different periods of averaging. According to accepted criteria a chart is bull-directed if the current value of the MA with smaller period is larger than the value of MA with larger period, and the difference between the values is larger than a certain value. In a bear movement MA with smaller period is lower than MA with larger period and the difference is also larger than a certain critical value.
At the block beginning values of MAs with averaging periods Period_MA_1 and Period_MA_2 are calculated. The fact of significance of any trading criterion is expressed via the value of a corresponding variable. Variables Opn_B and Opn_S denote the criterion triggering for opening Buy and Sell orders, variables Cls_В and Cls_S - for closing. For example, if a criterion for opening Buy has not triggered, the value of Opn_B remains 'false' (set at the variable initialization); if it has triggered, Opn_B gets the value 'true'. In this case the criterion for closing Sell coincides with that for opening Buy, criterion for opening Sell coincides with that for closing Buy.
Closing Orders.
It was written earlier that this Expert Advisor is intended for operation only with one market order opened for a security, to which window the EA is attached. To the moment when control in the program is passed to the order closing block it is known for sure that at the current moment there are either no orders for the security, or there is only one market order. That's why the code in orders closing block is written so that only one order can be closed successfully.
This block is based on the infinite loop 'while', the body of which consists of two analogous parts: one for closing a Buy order, another for closing a Sell order. 'While' is used here for the purpose that in case of a trade operation failure it could be repeated once again.
In the header of the first operator 'if' condition for closing a Buy order is calculated (Sell orders are closed in the analogous way). If the type of an earlier opened order corresponds to Buy (see Types of Trades) and the sign for closing Buy is relevant, control is passed to the body of 'if' operator where a request to close is formed. As an order closing price in the function OrderClose() the value of a two-sided quote corresponding to the order type is indicated (see Requirements and Limitations in Making Trades). If a trade operation is executed successfully, after a message about the order closing is shown the current 'while' iteration is stopped and the execution of the order closing block is over. But if the operation fails, the user-defined function for processing errors Fun_Error() is called (block 10-11).
Processing Errors.
As a passed parameter in Fun_Error() the last error code calculated by GetLastError() is used. Depending on the error code Fun_Error() returns 1 if the error is not critical and the operation can be repeated, and 0 if the error is critical. Critical errors are divided into two types - those, after which a program execution can be continued (for example, a common error) and those, after which execution of any trade operations must be stopped (for example, blocked account).
if after an unsuccessful trade operation the user-defined function returns 1, the current 'while' iteration is terminated and during the next iteration another attempt is made to execute the operation - to close the order. If the function returns 0, the current start() execution is stopped. On the next tick start() will be started by the client terminal again and if еору conditions for order closing are preserved, another attempt to close the order will be made.
If during error processing it is found out that further program execution is senseless (for example the program operates on an old client terminal version) during the next start the execution of the special function start() will be terminated in the block of preliminary processing when analyzing the value of the variable Work.
Calculating Amount of Lots for New Orders.
Amount of lots can be calculated in accordance with a user's settings following one of the two variants. The first variant is a certain constant value set up by a user. According to the second variant the amount of lots is calculated on the basis of a sum equal to a certain percentage (set by a user) of a free margin.
At the beginning of the block of defining the amount of lots for new orders (block 7-8) necessary values of some variables are calculated - minimal allowed amount of lots and step of lot change set up by a broker, free margin and price of one lot for the security.
In this example the following is provided. If a user has set up a certain non-zero value of the external variable Lts, for example 0.5, it is accepted as the amount of lots Lts when a trade request to open an order is formed. If 0 is assigned to Lts, the number of lots Lts is defined on the basis of the variable Prots (percentage), free margin and conditions set up by a broker.
After Lts is calculated, a check is conducted. If this value is lower than the minimal allowed value, the minimal allowed value is accepted. but if free margin is not enough, after a corresponding message the start() execution is terminated.
Opening Orders.
The block of opening orders (block 8-9) like the bloke of opening orders is an infinite loop 'while'. In the header of the first operator 'if' conditions for opening a Buy order are calculated: if there are no orders for the security (variable Total is equal to 0) and the sign for opening a Buy order is relevant (Opn_B is true ), control is passed to 'if' operator body for opening an order. In such a case after rates are refreshed prices for stop levels are calculated.
Values of stop levels are initially set by a user in external variables StopLoss and TakeProfit. In a general case a user can set values for this parameters smaller that a broker allows. Besides a broker may change the minimal allowed distance at any moment (it is an often case at strong market movements, for example, before important news release). That's why before each order opening stop levels must be calculate taking into account values set bu a user and the minimal allowed value set up by a broker.
For calculating stop levels the user-defined function New_Stop() is used; as a passed parameter the stop level value set by a user is used. In New_Stop() first the current minimal allowed distance is calculated. If the value set by a user corresponds to a broker's requirements, this value is returned. If it is smaller than the allowed value, the value allowed by a broker is used. Prices of stop requests are calculated from the corresponding two-sided quote (see Requirements and Limitations in Making Trades).
A trade request to open an order is formed using the function OrderSend(). For the calculation of order opening price and prices of stop requests the two-sided quote values corresponding to the order type are used. If a trade operation was successful (i. e. a server returned the number of an opened order) after a message about a successful order opening is shown. start() execution is finished. If an order was not opened and the client terminal returned an error, the error is processed according to the algorithm described earlier.
Some Code Peculiarities.
The analyzed Expert Advisor code is oriented to the implementation of a certain strategy. Note, some program lines contain variables and calculations that would be changed, if the strategy were changed.
For example, according to the accepted strategy the Expert Advisor is developed to work only with one order. This allowed to use the variable Ticket both for the identification of a closing order number (in block of closing 6-7) and for the identification of a success of a trade operation execution when opening an order (in the block of opening 8-9). In this case such a solution is acceptable. However, if we take the analyzed code as the basis for the implementation of another strategy (for example allow opposite orders) we will have to introduce one or several variables to be able to recognize numbers of opened orders and identify the success of trade operations.
In further strategy modifications we will have to change come program lines containing part of logics contained in the source strategy. Namely in the order accounting block we will not have to terminate the program operation if there are several open orders for a security. Besides, conditions for opening and closing orders will alslo change. This will entail the code changing in blocks of opening and closing orders.
Comments
Post a Comment