Large_Move_Indicator([sgnl];[sgnl_px];[dailyvol]) // function defined separately, source can be provided if needed. the outputs of the indicator are: signal, price upon signal, daily volatility //модификация сигмы на заданный интервал времени - Function which takes the daily volatility and scales it to the given time interval; volatility is an output of Large_Move_Indicator function (no need to do it, can provide for reference if necessary) scale_sigma(TFW,Large_Move_Indicator.[dailyvol]) { if(TFW>((FINISH_HOUR-START__HOUR) * 60.0)) { NB = 1440 / TFW; } else { NB = (FINISH_HOUR-START__HOUR) * 60.0 / TFW; } scale_sigma = Large_Move_Indicator.[dailyvol]/MathSqrt(DayCount * NB); //DayCount - convention: 360 or 365 days - defined in a separate function (no need to work on this) } *** Main Program Outline *** // Inputs input double init_sl_mult; // стоп лосс и тейк профит выражаются в качестве мультиплитатора сигм, рассчитывающихся через функцию scale_sigma - stop loss and take profit levels expressed as multiples of scaled volatility on specified timeframe input double init_tp_mult; // идентичная величина для тейк профита - identical as previous variable input double max_pos_time; // максимальное время в которое можно держать позицию открытой - max time to keep position open input double sl_adj_move; // шаг изменения цены, при котором подвигается стоп лосс - movement of price after which stop loss gets adjusted input double tp_adj_move; // шаг изменения цены, при котором подвигается тейк профит - same for take profit input double sl_adj_step; // размер, на который подвигается стоп лосс при движении цены на sl_adj_move пунктов - amount by which stop loss moves after px moves tp_adj_move points input double tp_adj_step; // размер, на который подвигается тейк профит при движении цены на tp_adj_move пунктов - identical to previous input double max_pos_sz; // максимальный размер позиции в штуках позиций (каждая размером pos_unit) - maximum position size input double pos_unit; // количество лотов за трейд - lots per trade input double order_devn; // максимальное отклонение от заданной цены - maximum price deviation from input double order_type; // тип заказа, FOK, OCO, LMT - order type // Declaration & Basic Calculation double init_sl_sz = init_sl_mult * scale_sigma(TFW); double init_tp_sz = init_tp_mult * scale_sigma(TFW); double pos_count = 0; // текущее количество открытых позиций - current number of open positions // Position class declaration position // свойства позиции, которые будут использоваться в коде - position properties to be used { position.dir; // 1 для лонг, -1 для шорт - 1 for long, -1 for short position.entrytime; // время, в которое открыта позиция - time of entry position.entryprice; // цена исполнения заявки - execution price position.sl_curr; // текущий уровень стоп лосса - current stop loss position.tp_curr; // текущий уровень тейк профита - current take profit position.sl_init; // первоначальный уровень стоп лосса- initial stop loss position.tp_init; // первоначальный уровень тейк профита - initial take profit } // Main Function OnTick { for (i=1;i<=max_pos_sz;i++) { check_sl_tp(); if (curr_time - position[i].entrytime)>= max_pos_time then close_pos(position[i]); //проверить, не достигнуто ли максимальное время, закрыть позицию, если достигнуто - check if max position keeping time has been reached adjust_sl_tp(position[i]); //adjust stop loss and take profit if time not exceeded if (signal(curr_time) = <>0 and MathAbs(pos_count) < max_posn) then open_pos(signal(curr_time)); } // Auxiliary functions close_pos //close position function, reset all the extra variables to zeros { ordersend(;;;;lmt = signalpx;deviation_tolerance = order_devn;) position.dir = 0; position.entrytime = 0; position.entryprice = 0; position.magicnumber = 0; position.tp_curr = 0; position.sl_curr = 0; position.sl_init = 0; position.tp_init = 0; } open_pos //open position function, record all main parameters here { ordersend(buy/sell;;;;lmt = signalpx;deviation_tolerance = order_devn) if buy then position.dir = 1 else position.dir = -1; position.entrytime = filled time; position.entryprice = filled price; position.magicnumber = EA_magic; position.sl_init = position.entryprice - position.dir * init_sl_sz; position.tp_init = position.entryprice + position.dir * init_tp_sz; position.tp_curr = position.tp_init; position.sl_curr = position.sl_init; pos_count+=position.dir; } check_sl_tp() { if (curr_price - position[i].sl_curr) * position[i].dir <= 0 then liquidate(position[i]); //проверить, не достигнут ли стоп лосс - check if take profit level reached if (position[i].tp_curr - curr_price) * position[i].dir <= 0 then liquidate(position[i]); //проверить, не достигнут ли тейк профит - check if stop loss level reached } adjust_sl_tp(position[i]) { position.tp_curr[i] = position.tp_init[i] + position[i].dir * tp_adj_step * (curr_price-position[i].entryprice)/tp_adj_move; //двигать тейк профит на х пунктов каждый раз когда спот двигается на y пунктов - move TP level x points when spot moves y points position.sl_curr[i] = position.sl_init[i] - position[i].dir * sl_ad_step * (curr_price-position[i].entryprice)/sl_adj_move; //двигать стоп лосс на х пунктов каждый раз когда спот двигается на y пунктов - move SL level x points when spot moves y points } *** Main Program Outline ***