Может он и желался для опционов,
но всё по коду оформлено только для форекс.
Для опционов должны быть совсем другие вызовы функций.
//+------------------------------------------------------------------+
//| Copyright © 2022, forex-time@mail.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2022, forex-time@mail.ru"
#property strict
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1 Yellow
#property indicator_color2 Green
#property indicator_color3 Red
#property indicator_width1 2
#property indicator_width2 2
#property indicator_width3 2
//+------------------------------------------------------------------+
extern int MA_Shift = 60;
extern int Ma_Period = 5;
extern int Ma_Method = 0;
extern int Ma_Price = 0;
extern double MA_Koef = 1.0;
//---- buffers
double CA[];
double UpBuffer[];
double DnBuffer[];
double Price[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
IndicatorBuffers(4);
SetIndexStyle(0,DRAW_LINE);
SetIndexStyle(1,DRAW_LINE);
SetIndexStyle(2,DRAW_LINE);
SetIndexBuffer(0,CA);
SetIndexBuffer(1,UpBuffer);
SetIndexBuffer(2,DnBuffer);
SetIndexDrawBegin(0,Ma_Period);
SetIndexDrawBegin(1,Ma_Period);
SetIndexDrawBegin(2,Ma_Period);
IndicatorShortName("CMA("+string(Ma_Period)+")");
SetIndexLabel(1,"UP");
SetIndexLabel(2,"DN");
return(0);}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start()
{
int i,limit;
int counted_bars=IndicatorCounted();
if (counted_bars<0) return(-1);
if (counted_bars>0) counted_bars--;
limit = MathMin(Bars-counted_bars,Bars-1);
if (counted_bars==0) {limit--; limit-=MA_Shift+1;} else limit++;
double K=0.0, v1=0.0, v2=0.0, MA=0.0;
for(i=limit; i>=0; i--)
{
CA[i]=Close[i]-Close[i+MA_Shift];
MA=iMAOnArray(CA,0,Ma_Period,0,Ma_Method,i);
v1=MA_Koef*MathSqrt(iStdDevOnArray(CA,0,Ma_Period,0,Ma_Method,i));
v2=MathSqrt(MathAbs(CA[i+1]-MA));
if (v2<v1 || v2==0.0) K=0.0; else K=1-(v1/v2);
if (CA[i]-CA[i+1] > 0) UpBuffer[i] = CA[i];
if (CA[i]-CA[i+1] < 0) DnBuffer[i] = CA[i];
}
return(0);}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Copyright © 2021, forex-time@mail.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, forex-time@mail.ru"
#property strict
//+------------------------------------------------------------------+
enum trade
{
Auto, //Авто
Fixed //Ручная
};
//+----------------+
extern trade MethodTrade = Auto; //Торговля МЕНЮ ==>>
extern double Lots = 0.1; //Фиксированный лот
extern double MaxLot = 5.0; //MAX лот
extern double KLot = 2.0; //Увеличение лота
extern double Profit = 15.0; //Закрыть общий профит $
extern double Loss = 0.0; //Общий убыток $ (=0 откл)
extern int TakeProfit = 0; //Тейк профит (=0 откл)
extern int DistNewOrd = 300; //Дистанция новый ордер
extern int MaxOrd = 10; //MAX ордеров
extern int Magic = 0; //Магик ордеров
extern string IndMA = "=== Moving Average ==="; //Индикатор ===>>
extern int PeriodMA = 20; //Период
extern int ShiftMA = 3; //Сдвиг линии
extern ENUM_MA_METHOD MethodMA = MODE_SMA; //Метод
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//Убрать сетку при тесте
if(IsTesting()) ChartSetInteger(0,CHART_SHOW_GRID,false);
return(INIT_SUCCEEDED);}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Comment("");}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//Закрытие ордеров
if(OP(-1)>0 && //Если есть ордера
(PrfOP(-1)>=Profit|| //Общий профит больше значения
(PrfOP(-1)<0 && Loss!=0.0 && MathAbs(PrfOP(-1))>=MathAbs(Loss))|| //Общий убыток больше значения
(OP(0)==0 && OP(1)==0))) //Нет открытых рыночных ордеров
DeleteAll(); //Закрыть и удалить все ордера
//Если выбран метод торговли АВТО
if(MethodTrade==Auto){
//Сигналы индикатора МА
int SignalMA=-1;
//Цена открытия текущей свечи выше МА и цена открытия предыдущей свечи ниже МА
if(Open[0]>MA(0) && Open[1]<=MA(1)) SignalMA=0;
//Цена открытия текущей свечи ниже МА и цена открытия предыдущей свечи выше МА
if(Open[0]<MA(0) && Open[1]>=MA(1)) SignalMA=1;
//Если нет ордеров, то открыть первый по сигналу МА
if(OP(-1)==0){
double TPb=0.0,TPs=0.0;
if(TakeProfit>0){
TPs=ND(Bid-TakeProfit*Point,Digits);
TPb=ND(Ask+TakeProfit*Point,Digits);
}
//Сигнал МА, открыть ордер в направлении
if(SignalMA==0) Send(OP_BUY,Lots,Ask,0,TPb,Blue);
if(SignalMA==1) Send(OP_SELL,Lots,Bid,0,TPs,Red);
}
}
//Если есть рыночные ордера то ставить отложенные
if((OP(0)>0||OP(1)>0) && OP(-1)<MaxOrd)
{
//Рассчитать тейк профит для отложенных
double TPb=0.0,TPs=0.0;
if(TakeProfit>0){
TPs=ND(LastPrcOP(0)-(DistNewOrd+TakeProfit)*Point,Digits);
TPb=ND(LastPrcOP(1)+(DistNewOrd+TakeProfit)*Point,Digits);
}
//Поставить отложенный противоположный последнему рыночному
int Spread=int(((Ask-Bid)/Point)*2); //Дистанция нового ордера должна быть больше спреда *2
if(DistNewOrd>0 && DistNewOrd>=Spread){
if(LastTypeOP()==0 && OP(5)==0) Send(OP_SELLSTOP,Lot(),ND(LastPrcOP(0)-DistNewOrd*Point,Digits),0,TPs,Red);
if(LastTypeOP()==1 && OP(4)==0) Send(OP_BUYSTOP,Lot(),ND(LastPrcOP(1)+DistNewOrd*Point,Digits),0,TPb,Blue);
}
}
}
//+------------------------------------------------------------------+
//| Индикатор Moving Average |
//+------------------------------------------------------------------+
double MA(int bar){
double ma=iMA(Symbol(),0, PeriodMA,ShiftMA,MethodMA,PRICE_CLOSE, bar);
return(ma);}
//+------------------------------------------------------------------+
//| Подсчет открытых ордеров по типу |
//+------------------------------------------------------------------+
int OP(int type=-1){
int op=0;
for(int i=OrdersTotal()-1;i>=0;i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol()){
if(OrderType()==type||type<0) op++;}
return(op);}
//+------------------------------------------------------------------+
//| Профит всех ордеров по типу |
//+------------------------------------------------------------------+
double PrfOP(int type=-1){
double pf=0.0;
for(int i=OrdersTotal()-1;i>=0;i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderType()<2 && OrderSymbol()==Symbol()){
if(OrderType()==type||type<0) pf+=OrderProfit()+OrderCommission()+OrderSwap();}
return(pf);}
//+------------------------------------------------------------------+
//| Цена последнего ордера по типу |
//+------------------------------------------------------------------+
double LastPrcOP(int type=-1){
double prc=0.0;
datetime t=0;
for(int i=OrdersTotal()-1;i>=0;i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol()){
if((OrderType()==type||type<0) && t<OrderOpenTime()) {t=OrderOpenTime(); prc=OrderOpenPrice();}}
return(prc);}
//+------------------------------------------------------------------+
//| Тип последнего ордера |
//+------------------------------------------------------------------+
int LastTypeOP(){
int type=-1;
datetime t=0;
for(int i=OrdersTotal()-1;i>=0;i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol()){
if(t<OrderOpenTime()) {t=OrderOpenTime(); type=OrderType();}}
return(type);}
//+------------------------------------------------------------------+
//| Расчёт лота |
//+------------------------------------------------------------------+
double Lot(){
double lot=0;
if(OP(-1)>0) lot=ND(Lots*MathPow(KLot,OP(-1)),2);
if(lot>MaxLot) lot=Lots;
return(lot);}
//+------------------------------------------------------------------+
//| ND - нормализация числа |
//-------------------------------------------------------------------+
double ND(double value, int digits) {
return(NormalizeDouble(value, digits));}
//+------------------------------------------------------------------+
//| Открытие, закрытие ордеров |
//+------------------------------------------------------------------+
void Send(int type, double lt, double price, double sl, double tp, color clr){
int send=0;
send=OrderSend(Symbol(),type,lt,price,30,sl,tp,"",Magic,0,clr);
if (send>0)
Print("Успешно открыт ордер "+TypeToStr(type),", Lot: "+(string)lt,", Ticket: "+(string)send,", Magic: "+(string)Magic);
else
Print("Невозможно открыть ордер "+TypeToStr(type),". Ошибка: "+string(GetLastError()));}
//+------------------------------------------------------------------+
void DeleteAll(){
color cls=Gray;
for(int i=OrdersTotal()-1; i>=0; i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol()){
if(OrderType()==OP_BUY) cls=DeepSkyBlue;
if(OrderType()==OP_SELL) cls=Magenta;
if(!OrderSelect(OrderTicket(),SELECT_BY_TICKET)||OrderCloseTime()>0) return;
if(OrderType()<2 && !OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),30,cls)) Print("Невозможно закрыть ордер "+TypeToStr(OrderType()),". Ошибка: "+string(GetLastError()));
if(OrderType()>1 && !OrderDelete(OrderTicket())) Print("Невозможно удалить ордер "+TypeToStr(OrderType()),". Ошибка: "+string(GetLastError()));}}
//+------------------------------------------------------------------+
string TypeToStr(int type) {
switch(type) {
case 0: return("Buy");
case 1: return("Sell");
case 2: return("BuyLimit");
case 3: return("SellLimit");
case 4: return("BuyStop");
case 5: return("SellStop");}
return("NONE");}
//-------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Copyright © 2021, forex-time@mail.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, forex-time@mail.ru"
#property strict
//+------------------------------------------------------------------+
enum trade
{
Auto, //Авто
Fixed //Ручная
};
//+----------------+
extern trade MethodTrade = Auto; //Торговля МЕНЮ ==>>
extern double Lots = 0.1; //Фиксированный лот
extern double MaxLot = 5.0; //MAX лот
extern double KLot = 2.0; //Увеличение лота
extern double Profit = 15.0; //Закрыть общий профит $
extern int TakeProfit = 0; //Тейк профит (=0 откл)
extern int DistNewOrd = 300; //Дистанция новый ордер
extern int MaxOrd = 10; //MAX ордеров
extern int Magic = 0; //Магик ордеров
extern string IndMA = "=== Moving Average ==="; //Индикатор ===>>
extern int PeriodMA = 20; //Период
extern int ShiftMA = 3; //Сдвиг линии
extern ENUM_MA_METHOD MethodMA = MODE_SMA; //Метод
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//Убрать сетку при тесте
if(IsTesting()) ChartSetInteger(0,CHART_SHOW_GRID,false);
return(INIT_SUCCEEDED);}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Comment("");}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(OP(-1)>0 && //Если есть ордера
(PrfOP(-1)>Profit|| //Общий профит больше значения
(OP(0)==0 && OP(1)==0))) //Нет открытых рыночных ордеров
DeleteAll(); //Закрыть и удалить все ордера
//Если выбран метод торговли АВТО
if(MethodTrade==Auto){
//Сигналы индикатора МА
int SignalMA=-1;
//Цена открытия текущей свечи выше МА и цена открытия предыдущей свечи ниже МА
if(Open[0]>MA(0) && Open[1]<=MA(1)) SignalMA=0;
//Цена открытия текущей свечи ниже МА и цена открытия предыдущей свечи выше МА
if(Open[0]<MA(0) && Open[1]>=MA(1)) SignalMA=1;
//Если нет ордеров, то открыть первый по сигналу МА
if(OP(-1)==0){
double TPb=0.0,TPs=0.0;
if(TakeProfit>0){
TPs=ND(Bid-TakeProfit*Point,Digits);
TPb=ND(Ask+TakeProfit*Point,Digits);
}
//Сигнал МА, открыть ордер в направлении
if(SignalMA==0) Send(OP_BUY,Lots,Ask,0,TPb,Blue);
if(SignalMA==1) Send(OP_SELL,Lots,Bid,0,TPs,Red);
}
}
//Если есть рыночные ордера то ставить отложенные
if((OP(0)>0||OP(1)>0) && OP(-1)<MaxOrd)
{
//Рассчитать тейк профит для отложенных
double TPb=0.0,TPs=0.0;
if(TakeProfit>0){
TPs=ND(LastPrcOP(0)-(DistNewOrd+TakeProfit)*Point,Digits);
TPb=ND(LastPrcOP(1)+(DistNewOrd+TakeProfit)*Point,Digits);
}
//Поставить отложенный противоположный последнему рыночному
int Spread=int(((Ask-Bid)/Point)*2); //Дистанция нового ордера должна быть больше спреда *2
if(DistNewOrd>0 && DistNewOrd>=Spread){
if(LastTypeOP()==0 && OP(5)==0) Send(OP_SELLSTOP,Lot(),ND(LastPrcOP(0)-DistNewOrd*Point,Digits),0,TPs,Red);
if(LastTypeOP()==1 && OP(4)==0) Send(OP_BUYSTOP,Lot(),ND(LastPrcOP(1)+DistNewOrd*Point,Digits),0,TPb,Blue);
}
}
}
//+------------------------------------------------------------------+
//| Индикатор Moving Average |
//+------------------------------------------------------------------+
double MA(int bar){
double ma=iMA(Symbol(),0, PeriodMA,ShiftMA,MethodMA,PRICE_CLOSE, bar);
return(ma);}
//+------------------------------------------------------------------+
//| Подсчет открытых ордеров по типу |
//+------------------------------------------------------------------+
int OP(int type=-1){
int op=0;
for(int i=OrdersTotal()-1;i>=0;i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol()){
if(OrderType()==type||type<0) op++;}
return(op);}
//+------------------------------------------------------------------+
//| Профит всех ордеров по типу |
//+------------------------------------------------------------------+
double PrfOP(int type=-1){
double pf=0.0;
for(int i=OrdersTotal()-1;i>=0;i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderType()<2 && OrderSymbol()==Symbol()){
if(OrderType()==type||type<0) pf+=OrderProfit()+OrderCommission()+OrderSwap();}
return(pf);}
//+------------------------------------------------------------------+
//| Цена последнего ордера по типу |
//+------------------------------------------------------------------+
double LastPrcOP(int type=-1){
double prc=0.0;
datetime t=0;
for(int i=OrdersTotal()-1;i>=0;i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol()){
if((OrderType()==type||type<0) && t<OrderOpenTime()) {t=OrderOpenTime(); prc=OrderOpenPrice();}}
return(prc);}
//+------------------------------------------------------------------+
//| Тип последнего ордера |
//+------------------------------------------------------------------+
int LastTypeOP(){
int type=-1;
datetime t=0;
for(int i=OrdersTotal()-1;i>=0;i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol()){
if(t<OrderOpenTime()) {t=OrderOpenTime(); type=OrderType();}}
return(type);}
//+------------------------------------------------------------------+
//| Расчёт лота |
//+------------------------------------------------------------------+
double Lot(){
double lot=0;
if(OP(-1)>0) lot=ND(Lots*MathPow(KLot,OP(-1)),2);
if(lot>MaxLot) lot=Lots;
return(lot);}
//+------------------------------------------------------------------+
//| ND - нормализация числа |
//-------------------------------------------------------------------+
double ND(double value, int digits) {
return(NormalizeDouble(value, digits));}
//+------------------------------------------------------------------+
//| Открытие, закрытие ордеров |
//+------------------------------------------------------------------+
void Send(int type, double lt, double price, double sl, double tp, color clr){
int send=0;
send=OrderSend(Symbol(),type,lt,price,30,sl,tp,"",Magic,0,clr);
if (send>0)
Print("Успешно открыт ордер "+TypeToStr(type),", Lot: "+(string)lt,", Ticket: "+(string)send,", Magic: "+(string)Magic);
else
Print("Невозможно открыть ордер "+TypeToStr(type),". Ошибка: "+string(GetLastError()));}
//+------------------------------------------------------------------+
void DeleteAll(){
color cls=Gray;
for(int i=OrdersTotal()-1; i>=0; i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol()){
if(OrderType()==OP_BUY) cls=DeepSkyBlue;
if(OrderType()==OP_SELL) cls=Magenta;
if(!OrderSelect(OrderTicket(),SELECT_BY_TICKET)||OrderCloseTime()>0) return;
if(OrderType()<2 && !OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),30,cls)) Print("Невозможно закрыть ордер "+TypeToStr(OrderType()),". Ошибка: "+string(GetLastError()));
if(OrderType()>1 && !OrderDelete(OrderTicket())) Print("Невозможно удалить ордер "+TypeToStr(OrderType()),". Ошибка: "+string(GetLastError()));}}
//+------------------------------------------------------------------+
string TypeToStr(int type) {
switch(type) {
case 0: return("Buy");
case 1: return("Sell");
case 2: return("BuyLimit");
case 3: return("SellLimit");
case 4: return("BuyStop");
case 5: return("SellStop");}
return("NONE");}
//-------------------------------------------------------------------+
Пишите на электронку, обсудим условия:
forex-time@mail.ru
forextime