gryps2/EA-code/TNK/MSK-008_XAUUSD_M5.mq4
super.admin ae3f0ebf03 convert
2025-05-30 14:58:21 +02:00

1378 lines
101 KiB
MQL4

//+------------------------------------------------------------------+
//| MSK-008_XAUUSD_M5.mq4 |
//| Copyright 2024, TNK/TNK_SYSTEM |
//| https://note.com/tnk_system |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, TNK/TNK_SYSTEM"
#property link "https://note.com/tnk_system"
#property version "1.0" // スワップ3倍戦術
#property icon "TNKIcon.ico" // アイコン取り込み
#property description "通貨ペア : XAUUSD"
#property description "時間足 : M5"
#property description "スタイル : 朝スキャ"
#property description "ポジション数 : 1"
#property description "両建て : 無し トレール : 無し"
#property description "TP/SL : 170/110pips(変更不可)"
#property description "週末持ち越し : 無し"
#property description "12/21~1/3 : 新規エントリー無し・決済のみ実行"
#property description "口座 : 日足5本(GMT冬+2/夏+3)専用"
#property strict
#include <stdlib.mqh>
//+------------------------------------------------------------------+
//|ユーザー入力用パラメーター |
//+------------------------------------------------------------------+
input int MagicNumber = 518911; // マジックナンバー(他EAと重複不可)
input double Lots = 0.10; // ロット(単利運用時)
input double MM_Risk = 1.0; // リスク%(複利選択項目の何%か)
enum MM_Select{
Fixed, // 0:単利/固定
FreeMargin, // 1:複利/余剰証拠金
Balance, // 2:複利/残高
};
input MM_Select MM_ON = Fixed; // 複利機能(0:固定/1:余剰証拠金/2:残高)
double MaxSpread_pips = 4.0; // 許容スプレッド(Pips)
input double AllowSpread = 10.0; // 許容スプレッドPips(0:自動)
//+------------------------------------------------------------------+
//|内部設定・グローバル関数 |
//+------------------------------------------------------------------+
//内部設定
int Maxposition = 1; // 最大ポジション
int Slippage = 100; // 許容スリッページ(Point)
bool YearendClose = true; // 12/21~1/3クローズ
string _Comment = "MSK-008_XAUUSD_M5"; // 通知用コメント
//桁合わせ・時間制御用
double xpoint;
int xxTime, yTime;
//エントリー時間(サーバー時間)
bool GMT_Kadou_OK_L1 = false; // エントリー時間
//ポジション決済(サーバー時間)
bool PositionClose_L1 = false; // ポジション決済(買い)
bool TimeClose = false;
//バックテスト用モード切替
bool Development = false; // 開発モードON/OFF(OnTester欄にRF表示、インジケータ表示)
//+------------------------------------------------------------------+
//|便利機能系 |
//+------------------------------------------------------------------+
//チャートセット固定用
string SYMBOL1 = "XAUUSD"; // シンボル名(頭6文字)
string SYMBOL2 = "GOLD"; // シンボル名(頭4文字)
int Chart_TimeFrame = PERIOD_M5; // タイムフレーム
// EAの状態変化用
bool ChartWarning;
// チャートにトレード履歴表示用
double tes = 0.0; // 外付け手数料(PIPS換算)
int sf, tof;
datetime hf;
double totalpips = 0, ProfitFactor = 0;
double plus_profit = 0, minus_profit = 0;
double minus_count = 0, plus_count = 0;
double RRR, WinPer;
double TradeCounts;
// マジックナンバー重複セットアラート
static bool check_duplicate = true;
static const string kEA_NAME = (string)MagicNumber;
// スプレッド計測用
double MeasureSpread, SpreadMin = 1000, SpreadMax = 0, SpreadSum = 0, SpreadAve = 0;
int TickCount = 0, lastBars;
// オートスプレッド用
double Adjustspread = 5.0; // 平均スプレッド加算用宣言
double AllowMaxSpread = 5.0; // 自動最大許容スプレッド
double Adjustspread_Margin = 0.5; // 自動スプレッド調整幅
// 証拠金チェック
int aCmd = 0;
// DPI換算
double DPIAdjust;
// バックテスト時間計測
uint StartingTimestamp;
// GMT0ブローカー禁止・サマータイム自動調整
string BrokerName0 = "Ava Trad"; // Ava "Ava Trade Ltd.";
string BrokerName1 = "Exness T"; // Exness "Exness Technologies Ltd";
/*string BrokerName2 = "HF Marke"; // HFM "HF Markets (SV) Ltd.";"HF Markets(SV)Ltd.";
string BrokerName3 = "Tradexfi"; // XM "Tradexfin Limited";
string BrokerName4 = "FinTrade"; // XM "FinTrade Limited";
string BrokerName5 = "NOTESCO "; // IronFX "NOTESCO Ltd";
*/
//+------------------------------------------------------------------+
//|ロジック用パラメータ |
//+------------------------------------------------------------------+
bool Logic1 = true; // 【稼働スイッチ】
//オープントリガー
int TimeOpen_L1 = 23; // 【オープン】時刻
int MinuteOpen_L1 = 30; // 【オープン】分
//決済トリガー
int TimeClose_L1 = 1; // 【決済】時刻
int MinuteClose_L1 = 0; // 【決済】分
int TimeCloseLimit = 1; // 【決済】強制決済時刻
int MinuteCloseLimit = 59; // 【決済】強制決済分
int TakeProfit_pips = 170; // 【決済】TakeProfit(Pips)
int StopLoss_pips = 60; // 【決済】StopLoss(Pips)
//エントリーフィルター
double Gap_Pips = 3.0; // 【フィルター】1本前ローソク足終値と現在価格の差pips
bool Filter = true; // 【フィルター】MA/SDフィルターON/OFF
ENUM_TIMEFRAMES MA_TF_buy = PERIOD_M5; // 【フィルター】MAタイムフレーム
int MA_period_buy = 185; // 【フィルター】MA期間
ENUM_TIMEFRAMES SD_TF = PERIOD_M5; // 【フィルター】SDタイムフレーム
int SD_Period = 20; // 【フィルター】SD期間
double SD_Line = 0.8; // 【フィルター】SDライン
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| tester function |
//+------------------------------------------------------------------+
double OnTester()
{
// OnTesterに表示【リカバリーファクター|勝率】
if (Development)
{
// リカバリーファクター
return(NormalizeDouble(TesterStatistics(STAT_PROFIT) / TesterStatistics(STAT_EQUITY_DD), 2));
}
return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//+------------------------------------------------------------------+
// バックテスト時間計測
StartingTimestamp = GetTickCount();
//+------------------------------------------------------------------+
// GMT0ブローカー稼働禁止
if (StringSubstr(AccountCompany(), 0, 8) == BrokerName0
|| StringSubstr(AccountCompany(), 0, 8) == BrokerName1
)
{
Alert(
WindowExpertName() + " cannot run on brokers at GMT0"
+ "\n"
+ "GMT0のブローカーは稼働できません"
);
return(INIT_FAILED);
}
//+------------------------------------------------------------------+
// 小数点以下の桁数に応じてPipsの値を調整する
xpoint = Point();
if (StringSubstr(Symbol(), 0, 6) == "XAUUSD" || StringSubstr(Symbol(), 0, 4) == "GOLD") // ゴールド用
{
if (Digits() == 2)
{
xpoint = xpoint * 10;
}
else if (Digits() == 3)
{
xpoint = xpoint * 100;
}
}
else if (StringSubstr(Symbol(), 0, 6) == "USDMXN") // メキシコペソ用
{
if (Digits() == 4)
{
xpoint = xpoint * 10;
}
else if (Digits() == 5)
{
xpoint = xpoint * 100;
}
}
else if (!(StringSubstr(Symbol(), 0, 6) == "XAUUSD" || StringSubstr(Symbol(), 0, 4) == "GOLD"
|| StringSubstr(Symbol(), 0, 6) == "USDMXN")) // ゴールド・メキシコペソ以外用
{
if (Digits() == 3 || Digits() == 5)
{
xpoint = xpoint * 10;
}
}
//+-----------------------------------------------------------------+
// DPI換算
double USERdpi = TerminalInfoInteger(TERMINAL_SCREEN_DPI);
double DevPCdpi = 144;
DPIAdjust = USERdpi / DevPCdpi;
//+------------------------------------------------------------------+
// 最大SL算出(コメント・複利の計算で使用)
//TakeProfit_pips = MathMax(TakeProfit_pips_L1, TakeProfit_pips_L2);
//StopLoss_pips = MathMax(StopLoss_pips_L1, StopLoss_pips_L2);
//+------------------------------------------------------------------+
// 初期化スプレッド(バックテスト時または手動時、それ以外や自動)
if (IsTesting() || AllowSpread != 0) MaxSpread_pips = AllowSpread;
if (AllowSpread == 0) MaxSpread_pips = AllowMaxSpread;
//+------------------------------------------------------------------+
// チャート自動変更・シンボル・チャートコメント・状態表示
if (!IsTesting())
{
ChartSet(); // チャート自動変更
CenterSymbol(); // 中央のシンボル
ChartComment(); // チャートコメント
}
//+------------------------------------------------------------------+
// トレード履歴をチャートに表示(ライン・pips)
history();
PosHis();
//+------------------------------------------------------------------+
// 開発モード(販売時はfalseに)
if (Development) HideTestIndicators(false);// 使用しているインジケータを表示する
else HideTestIndicators(true);// 使用しているインジケータを非表示にする
//+------------------------------------------------------------------+
// マジックナンバー重複セットアラート
if (check_duplicate)
{
double term_global_var;
if (GlobalVariableGet(kEA_NAME, term_global_var))
{
Alert(
WindowExpertName() + " may have duplicate magic numbers. If all is well, press OK to continue with the setup"
+ "\n"
+ "マジックナンバー重複の可能性があります。問題が無ければ、OKを押して設定を継続してください。"
);
}
const datetime mutex_time = GlobalVariableSet(kEA_NAME, 1.0);
if (mutex_time == 0)
{
const int errcode = GetLastError();
Print("GlobalVariableSet: ERRCODE[", errcode, "]:", ErrorDescription(errcode));
}
}
//+------------------------------------------------------------------+
return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| expert OnDeinit function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//+------------------------------------------------------------------+
// オブジェクト削除関連
if (!IsTesting())
{
ObjectsDeleteAll();
ChartSetInteger(0,CHART_COLOR_CHART_UP,clrLime);
ChartSetInteger(0,CHART_COLOR_CHART_DOWN,clrLime);
ChartSetInteger(0,CHART_COLOR_CHART_LINE,clrLime);
Comment("");
}
//+------------------------------------------------------------------+
// マジックナンバー重複用
if (check_duplicate)
{
if (!GlobalVariableDel(kEA_NAME))
{
const int errcode = GetLastError();
Print("GlobalVariableDel: ERRCODE[", errcode, "]:", ErrorDescription(errcode));
}
}
//+------------------------------------------------------------------+
// バックテスト時間計算・出力
if (IsTesting())
{
uint EndingTimestamp = GetTickCount(); //始動時間
uint BT_Time = EndingTimestamp - StartingTimestamp;
uint msec_unit = BT_Time % 1000;
datetime temp_date = BT_Time / 1000;
Print( "バックテスト時間= ",
TimeHour(temp_date), "hour ",
TimeMinute(temp_date), "min ",
TimeSeconds(temp_date), ".", msec_unit, "sec ",
" 元データ= ", BT_Time );
}
//+------------------------------------------------------------------+
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//if (Volume[0] <= 10)
{
GetSummertimeShift(); // サマータイム調整・時間制御
if (PositionClose_L1) {PositionClose();} // ポジションをクローズ
if (GMT_Kadou_OK_L1) {PositionOpen();} // ポジションのエントリー
}
//if (Volume[0] == 11) {SetTPSL();} // TP, SLの再設定
//+------------------------------------------------------------------+
// チャート自動変更・シンボル・チャートコメント・状態表示
if (!IsTesting())
{
CenterSymbol(); // センターにシンボル情報
ChartComment(); // チャートコメント
}
//+------------------------------------------------------------------+
// スプレッド値取得
if (!IsTesting() && AllowSpread == 0)
{
MeasureSpread = MarketInfo(Symbol(),MODE_SPREAD) / 10;
MeasureSP();
}
//+------------------------------------------------------------------+
// チャートにトレード線とpips表示
if (!IsTesting() || IsVisualMode())
{
if (sf != Seconds() && OrdersTotal() > 0)
{
PosHis();
sf = Seconds();
}
if ((hf != iTime((string)0, 60, 0) && Seconds() > 30) || tof != OrdersHistoryTotal())
{
history();
hf = iTime((string)0, 60, 0);
tof = OrdersHistoryTotal();
}
}
//+------------------------------------------------------------------+
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| 時間制御 |
//+------------------------------------------------------------------+
void GetSummertimeShift()
{
//---- トレード許可時間の判定 ----
xxTime = TimeHour(TimeCurrent()); // サーバー時間(サマータイム計算なし)
yTime = TimeMinute(TimeCurrent()); // サーバーの分
// サーバー時間
if (xxTime < 0)
{
xxTime = xxTime + 24;
}
else if (xxTime > 23)
{
xxTime = xxTime - 24;
}
if (Logic1)
{
// ポジションクローズ時間(サーバー時間)
if ((xxTime == TimeClose_L1 && yTime >= MinuteClose_L1)
|| (xxTime > TimeClose_L1 && xxTime < TimeOpen_L1)
)
{
PositionClose_L1 = true;
}
else
{
PositionClose_L1 = false;
}
if (xxTime == TimeCloseLimit && yTime == MinuteCloseLimit)
{
TimeClose = true;
}
else
{
TimeClose = false;
}
// エントリー時間(サーバー時間)
if (xxTime >= TimeOpen_L1 && yTime >= MinuteOpen_L1
)
{
GMT_Kadou_OK_L1 = true;
}
else
{
GMT_Kadou_OK_L1 = false;
}
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| ポジションのクローズ |
//+------------------------------------------------------------------+
void PositionClose()
{
int i;
double profit;
bool res;
// 所有しているポジションをクローズする
for(i=OrdersTotal()-1; i>=0; i--)
{
//オーダー選択(エラーを生じた場合、ループから抜け出す)
if (OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) == false)
{
Print("OrderSelect returned the error of ", GetLastError() );
break;
}
//オーダー確認(通貨ペアが一致しない場合は、for文の先頭に戻る)
if (OrderSymbol() != Symbol()) continue;
//マジックナンバー確認(マジックナンバーが一致しない場合は、for文の先頭に戻る)
if (OrderMagicNumber() != MagicNumber) continue;
//エントリーからのローソク足本数が1本未満なら、for文の先頭に戻る)
int OrderOpenCandleCount = iBarShift(NULL, PERIOD_M5, OrderOpenTime());
if (OrderOpenCandleCount == 0) continue;
if (OrderType() == OP_BUY)
{
profit = Bid - OrderOpenPrice(); // 買いポジションだった場合の、含み損益を計算する
// オーダーを成り行き決済する
if (
(Exit2(false) == 2 && Ask - Bid <= MaxSpread_pips * xpoint)
|| (Exit2(false) == 2 && Ask - Bid > MaxSpread_pips * xpoint && profit > 0)
|| TimeClose
)
{
res = OrderClose(OrderTicket(), OrderLots(), Bid, NULL, Green);
}
}
if (OrderType() == OP_SELL)
{
profit = OrderOpenPrice() - Ask; // 売りポジションだった場合の、含み損益を計算する
// オーダーを成り行き決済する
if (
(Exit1(true) == 1 && Ask - Bid <= MaxSpread_pips * xpoint)
|| (Exit1(true) == 1 && Ask - Bid > MaxSpread_pips * xpoint && profit > 0)
|| TimeClose
)
{
res = OrderClose(OrderTicket(), OrderLots(), Ask, NULL, Green);
}
}
} // 所有しているポジションをクローズする(ココマデ)
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| ポジションのオープン |
//+------------------------------------------------------------------+
void PositionOpen()
{
int i, j;
int ticket;
int CountBuy = 0,CountSell = 0;
bool res;
int OrderOpen_BarCount_buy = 1; // 0にすると、履歴無いときにエントリーしないため、他の値を初期値にする
int OrderOpen_BarCount_sell = 1;
int OrderClose_BarCount_buy = 1; // 0にすると、履歴無いときにエントリーしないため、他の値を初期値にする
int OrderClose_BarCount_sell = 1;
// ポジションの数をカウントする
for(i=OrdersTotal()-1; i>=0; i--)
{
//オーダー選択(エラーを生じた場合、ループから抜け出す)
if (OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) == false)
{
Print("OrderSelect returned the error of ", GetLastError() );
break;
}
//オーダー確認(通貨ペアが一致しない場合は、for文の先頭に戻る)
if (OrderSymbol() != Symbol()) continue;
//マジックナンバー確認(マジックナンバーが一致しない場合は、for文の先頭に戻る)
if (OrderMagicNumber() != MagicNumber) continue;
if (OrderType() == OP_BUY)
{
CountBuy = CountBuy + 1;
}
if (OrderType() == OP_SELL)
{
CountSell = CountSell + 1;
}
aCmd = OrderType();
} // ポジションの数をカウントする(ココマデ)
// 最終エントリー・決済からのローソク足本数をカウントする
for(j=OrdersHistoryTotal()-1; j>=0; j--)
{
//オーダー選択(エラーを生じた場合、ループから抜け出す)
if (OrderSelect( j, SELECT_BY_POS, MODE_HISTORY ) == false)
{
Print("OrderSelect returned the error of ", GetLastError() );
break;
}
//オーダー確認(通貨ペアが一致しない場合は、for文の先頭に戻る)
if (OrderSymbol() != Symbol()) continue;
//マジックナンバー確認(マジックナンバーが一致しない場合は、for文の先頭に戻る)
if (OrderMagicNumber() != MagicNumber) continue;
//最終エントリー・決済からのローソク足本数
if (OrderType() == OP_BUY) // 買いの場合
{
OrderOpen_BarCount_buy = iBarShift(NULL, PERIOD_M5, OrderOpenTime());
OrderClose_BarCount_buy = iBarShift(NULL, PERIOD_M5, OrderCloseTime());
if (OrderClose_BarCount_buy != -1) break; // 一度最終決済を抽出したらループから抜ける
}
if (OrderType() == OP_SELL) // 売りの場合
{
OrderOpen_BarCount_sell = iBarShift(NULL, 0, OrderOpenTime());
OrderClose_BarCount_sell = iBarShift(NULL, 0, OrderCloseTime());
if (OrderClose_BarCount_sell != -1) break; // 一度最終決済を抽出したらループから抜ける
}
} // 最終エントリー・決済からのローソク足本数をカウントする(ココマデ)
// 証拠金不足・トレード許可チェック
if (EquityCheck())
{
// エントリー条件を確認し、成立していればエントリーを行う
if (Entry(true) == 1 // 買いエントリー
&& CountBuy < Maxposition
&& Exit2(false) != 2 // 買い決済シグナル無し
)
{
ticket = OrderSend(Symbol(),
OP_BUY,
CalculateLots(MM_Risk, StopLoss_pips),
Ask,
Slippage,
Ask - StopLoss_pips * xpoint,
Ask + TakeProfit_pips * xpoint,
_Comment,
MagicNumber,
0,
Blue);
// エントリーが失敗であれば、TPSLを分割して注文する
if (ticket == -1)
{
ticket = OrderSend(Symbol(),
OP_BUY,
CalculateLots(MM_Risk, StopLoss_pips),
Ask,
Slippage,
0,
0,
_Comment,
MagicNumber,
0,
Blue);
// エントリーに成功していれば、TP, SLをセットする
if (ticket != -1)
{
// チケットを使ってオーダーを選択(エラーを生じた場合、何もしない)
if( OrderSelect( ticket, SELECT_BY_TICKET ) == true )
{
res = OrderModify(OrderTicket(),
OrderOpenPrice(),
OrderOpenPrice() - StopLoss_pips * xpoint,
OrderOpenPrice() + TakeProfit_pips * xpoint,
0, MediumSeaGreen);
}
}
}
}
if (Entry(false) == 2 // 売りエントリー
&& CountSell < Maxposition
&& Exit1(true) != 1 // 売り決済シグナル無し
)
{
ticket = OrderSend(Symbol(),
OP_SELL,
CalculateLots(MM_Risk, StopLoss_pips),
Bid,
Slippage,
Bid + StopLoss_pips * xpoint,
Bid - TakeProfit_pips * xpoint,
_Comment,
MagicNumber,
0,
Red);
// エントリーが失敗であれば、TPSLを分割して注文する
if (ticket == -1)
{
ticket = OrderSend(Symbol(),
OP_SELL,
CalculateLots(MM_Risk, StopLoss_pips),
Bid,
Slippage,
0,
0,
_Comment,
MagicNumber,
0,
Red);
// エントリーに成功していれば、TP, SLをセットする
if (ticket != -1)
{
// チケットを使ってオーダーを選択(エラーを生じた場合、何もしない)
if( OrderSelect( ticket, SELECT_BY_TICKET ) == true )
{
res = OrderModify(OrderTicket(),
OrderOpenPrice(),
OrderOpenPrice() + StopLoss_pips * xpoint,
OrderOpenPrice() - TakeProfit_pips * xpoint,
0, MediumSeaGreen);
}
}
}
}
}
}
//+------------------------------------------------------------------+
bool EquityCheck()
{
// 証拠金不足・トレード許可チェック
double usedMoney = AccountEquity() - AccountFreeMarginCheck(Symbol(), aCmd, CalculateLots(MM_Risk, StopLoss_pips));
if (!(
(AccountStopoutMode() == 0 && usedMoney > 0.0 && (AccountEquity() / usedMoney) * 100 <= AccountStopoutLevel())
|| (AccountStopoutMode() == 0 && usedMoney > 0.0 && AccountFreeMarginCheck(Symbol(), aCmd, CalculateLots(MM_Risk, StopLoss_pips)) <= 0)
|| (AccountStopoutMode() == 1 && AccountFreeMarginCheck(Symbol(), aCmd, CalculateLots(MM_Risk, StopLoss_pips)) <= AccountStopoutLevel())
)
&& IsTradeAllowed() == true) // トレード許可判定
{
return(true);
}
else return(false);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| TakeProfit, StopLoss |
//+------------------------------------------------------------------+
void SetTPSL()
{
int i;
double profit;
bool res;
// ポジションにTP, SLをセットする
for(i=OrdersTotal()-1; i>=0; i--)
{
//オーダー選択(エラーを生じた場合、ループから抜け出す)
if (OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) == false)
{
Print("OrderSelect returned the error of ", GetLastError() );
break;
}
//オーダー確認(通貨ペアが一致しない場合は、for文の先頭に戻る)
if (OrderSymbol() != Symbol()) continue;
//マジックナンバー確認(マジックナンバーが一致しない場合は、for文の先頭に戻る)
if (OrderMagicNumber() != MagicNumber) continue;
// 買いポジションの場合
if (OrderType() == OP_BUY)
{
profit = Bid - OrderOpenPrice(); // 買いポジションだった場合の、含み損益を計算する
// TP, SLがどちらも設定されていなければ、TP, SLを設定する
if (OrderStopLoss() == 0 && OrderTakeProfit() == 0)
{
res = OrderModify(OrderTicket(), OrderOpenPrice(),
OrderOpenPrice() - StopLoss_pips * xpoint,
OrderOpenPrice() + TakeProfit_pips * xpoint,
0, MediumSeaGreen);
}
}
// 売りポジションの場合
if (OrderType() == OP_SELL)
{
profit = OrderOpenPrice() - Ask; // 売りポジションだった場合の、含み損益を計算する
// TP, SLがどちらも設定されていなければ、TP, SLを設定する
if (OrderStopLoss() == 0 && OrderTakeProfit() == 0)
{
res = OrderModify(OrderTicket(), OrderOpenPrice(),
OrderOpenPrice() + StopLoss_pips * xpoint,
OrderOpenPrice() - TakeProfit_pips * xpoint,
0, MediumSeaGreen);
}
}
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| 複利機能 |
//+------------------------------------------------------------------+
// 複利機能のロット数を計算する
double CalculateLots(double risk, // 許容するリスク
int sl_pips) // ストップロス
{
// バックテスト時は、バックテスト用の複利機能を使用する
if (IsTesting())
return(CalculateLots_forTest(risk, sl_pips));
else
return(CalculateLots_forReal(risk, sl_pips));
}
// 複利機能のロット数を計算する(実トレード用)
double CalculateLots_forReal(double risk, // 許容するリスク
int sl_pips) // ストップロス
{
double freemargin; // アカウントの余剰証拠金
double balance; // アカウントの口座残高
double credit; // アカウントのクレジット
double tickvalue; // 1ロット1pip当たりの証拠金通貨相当額
double lotstep; // サーバのロット数の最小刻み制限
double maxlots; // サーバの最大ロット数制限
double minlots; // サーバの最小ロット数制限
double lotsize = Lots; // ロットサイズ
freemargin = AccountFreeMargin();
balance = AccountBalance();
credit = AccountCredit();
tickvalue = MarketInfo(NULL, MODE_TICKVALUE);
lotstep = MarketInfo(NULL, MODE_LOTSTEP);
maxlots = MarketInfo(NULL, MODE_MAXLOT);
minlots = MarketInfo(NULL, MODE_MINLOT);
// 複利機能を使わない場合、Lotsから修正されたlotsizeを返す
int step = (int)MathAbs(MathLog10(MarketInfo(Symbol(), MODE_LOTSTEP)));
lotsize = NormalizeDouble(Lots, (int)step); //ロットステップで四捨五入
lotsize = MathMax(minlots, MathMin(maxlots, lotsize)); //最小ロット以下なら最小ロットに、最大ロット以上なら最大ロットに修正
if (MM_ON == Fixed) return(lotsize);
// tickvalueはpipsではなくpointなので、小数点以下の桁数に応じて補正する
if (StringSubstr(Symbol(), 0, 6) == "XAUUSD" || StringSubstr(Symbol(), 0, 4) == "GOLD")
{
if (Digits() == 2)
tickvalue = tickvalue * 10;
else if (Digits() == 3)
tickvalue = tickvalue * 100;
}
else if (StringSubstr(Symbol(), 0, 6) == "USDMXN") // メキシコペソ用
{
if (Digits() == 4)
tickvalue = tickvalue * 10;
else if (Digits() == 5)
tickvalue = tickvalue * 100;
}
else if (!(StringSubstr(Symbol(), 0, 6) == "XAUUSD" || StringSubstr(Symbol(), 0, 4) == "GOLD"
|| StringSubstr(Symbol(), 0, 6) == "USDMXN")) // ゴールド・メキシコペソ以外用
{
if (Digits() == 3 || Digits() == 5)
tickvalue = tickvalue * 10;
}
// 許容するリスクとSLの幅から、ロットサイズを計算する。
if (MM_ON == FreeMargin) // 余剰証拠金方式
{
lotsize = (freemargin * risk / 100.0) // 許容するリスク (余剰証拠金のrisk%)
/ (sl_pips * tickvalue); // 1ロットでSLにかかった時の金額
}
else if (MM_ON == Balance) // 残高方式
{
lotsize = ((balance + credit) * risk / 100.0) // 許容するリスク (余剰証拠金のrisk%)
/ (sl_pips * tickvalue); // 1ロットでSLにかかった時の金額
}
// サーバのロット数の刻みに合わせてロット数を修正
lotsize = MathFloor(lotsize / lotstep) * lotstep;
// サーバの最小ロット数・最大ロット数で補正をかける
lotsize = MathMax(lotsize, minlots);
lotsize = MathMin(lotsize, maxlots);
return(lotsize);
}
// 複利機能のロット数を計算する(バックテスト用)
double CalculateLots_forTest(double risk, // 許容するリスク
int sl_pips) // ストップロス
{
double freemargin; // アカウントの余剰証拠金
double balance; // アカウントの口座残高
double credit; // アカウントのクレジット
double tickvalue; // 1ロット1pip当たりの証拠金通貨相当額
double lotstep; // サーバのロット数の最小刻み制限
double maxlots; // サーバの最大ロット数制限
double minlots; // サーバの最小ロット数制限
double lotamount; // 1ロットの通貨数
double lotsize = Lots; // ロットサイズ
double conv; // 口座通貨種類による補正係数
freemargin = AccountFreeMargin();
balance = AccountBalance();
credit = AccountCredit();
tickvalue = MarketInfo(NULL, MODE_TICKVALUE);
lotstep = MarketInfo(NULL, MODE_LOTSTEP);
maxlots = MarketInfo(NULL, MODE_MAXLOT);
minlots = MarketInfo(NULL, MODE_MINLOT);
lotamount = MarketInfo(NULL, MODE_LOTSIZE);
// 複利機能を使わない場合、Lotsから修正されたlotsizeを返す
int step = (int)MathAbs(MathLog10(MarketInfo(Symbol(), MODE_LOTSTEP)));
lotsize = NormalizeDouble(Lots, step); //ロットステップで四捨五入
lotsize = MathMax(minlots, MathMin(maxlots, lotsize)); //最小ロット以下なら最小ロットに、最大ロット以上なら最大ロットに修正
if (MM_ON == Fixed) return(lotsize);
// 1万通貨*1pips = $1 = 100円と仮定し、1ロット1pipの変動が口座通貨でいくらに相当するか計算
// 1 lot = 10万通貨
// 口座通貨 = JPY : tickvalue = 1000円/(lot・pip)
// 口座通貨 = USD : tickvalue = $10/(lot・pip)
if (StringSubstr(Symbol(), 0, 6) == "XAUUSD" || StringSubstr(Symbol(), 0, 4) == "GOLD")
{
conv = 1000;
if (AccountCurrency() == "JPY")
conv = 100000;
tickvalue = lotamount / 10000 * conv;
}
else if (StringSubstr(Symbol(), 0, 6) == "USDMXN") // メキシコペソ用
{
conv = 1;
if (AccountCurrency() == "JPY")
conv = 100;
tickvalue = lotamount / 10000 * conv;
}
else if (!(StringSubstr(Symbol(), 0, 6) == "XAUUSD" || StringSubstr(Symbol(), 0, 4) == "GOLD"
|| StringSubstr(Symbol(), 0, 6) == "USDMXN")) // ゴールド・メキシコペソ以外用
{
conv = 1;
if (AccountCurrency() == "JPY")
conv = 100;
tickvalue = lotamount / 10000 * conv;
}
// 許容するリスクとSLの幅から、ロットサイズを計算する。
if (MM_ON == FreeMargin) // 余剰証拠金方式
{
lotsize = (freemargin * risk / 100.0) // 許容するリスク (余剰証拠金のrisk%)
/ (sl_pips * tickvalue); // 1ロットでSLにかかった時の金額
}
else if (MM_ON == Balance) // 残高方式
{
lotsize = ((balance + credit) * risk / 100.0) // 許容するリスク (余剰証拠金のrisk%)
/ (sl_pips * tickvalue); // 1ロットでSLにかかった時の金額
}
// サーバのロット数の刻みに合わせてロット数を修正
lotsize = MathFloor(lotsize / lotstep) * lotstep;
// サーバの最小ロット数・最大ロット数で補正をかける
lotsize = MathMax(lotsize, minlots);
lotsize = MathMin(lotsize, maxlots);
return(lotsize);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| エントリー総括 |
//+------------------------------------------------------------------+
int Entry(bool isbuy)
{
if (Entry_Rule1(isbuy) == 1 && (Entry_Filter1(isbuy) == 1 || Entry_Filter1(isbuy) == 3)
&& (Entry_Filter2(isbuy) == 1 || Entry_Filter2(isbuy) == 3)
&& (Entry_Filter3(isbuy) == 1 || Entry_Filter3(isbuy) == 3)
)
{
return(1);
}
else if (Entry_Rule1(isbuy) == 2 && (Entry_Filter1(isbuy) == 2 || Entry_Filter1(isbuy) == 3)
&& (Entry_Filter2(isbuy) == 2 || Entry_Filter2(isbuy) == 3)
&& (Entry_Filter3(isbuy) == 2 || Entry_Filter3(isbuy) == 3)
)
{
return(2);
}
else
{
return(0);
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| 売りポジションの決済総括 |
//+------------------------------------------------------------------+
int Exit1(bool isbuy)
{
if (Exit_Rule1(isbuy) == 3)
{
return(0);
}
else if (Exit_Rule1(isbuy) == 1)
{
return(1);
}
else
{
return(0);
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| 買いポジションの決済総括 |
//+------------------------------------------------------------------+
int Exit2(bool isbuy)
{
if (Exit_Rule1(isbuy) == 3)
{
return(0);
}
else if (Exit_Rule1(isbuy) == 2)
{
return(2);
}
else
{
return(0);
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| エントリールール1 |
//+------------------------------------------------------------------+
int Entry_Rule1(bool isbuy)
{
//エントリールール1
// 時間制御によるエントリー可能時間でエントリー判定
if (!isbuy && GMT_Kadou_OK_L1)
{
return(2);
} // 買い
return(0); // エントリー出来ない
//エントリールール1ココマデ
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| エントリーフィルター1 |
//+------------------------------------------------------------------+
int Entry_Filter1(bool isbuy)
{
//エントリーフィルター1
// 固定仕様系
// スプレッドフィルター
double spread = MarketInfo(NULL, MODE_SPREAD);
if (StringSubstr(Symbol(), 0, 6) == "XAUUSD" || StringSubstr(Symbol(), 0, 4) == "GOLD") // ゴールド桁合わせ
{
if (Digits() == 2) spread /= 10.0;
else if (Digits() == 3) spread /= 100.0;
}
else if (StringSubstr(Symbol(), 0, 6) == "USDMXN") // メキシコペソ用
{
if (Digits() == 4) spread /= 10.0;
if (Digits() == 5) spread /= 100.0;
}
else if (!(StringSubstr(Symbol(), 0, 6) == "XAUUSD" || StringSubstr(Symbol(), 0, 4) == "GOLD"
|| StringSubstr(Symbol(), 0, 6) == "USDMXN")) // ゴールド・メキシコペソ以外用
{
if (Digits == 3 || Digits == 5) spread /= 10.0;
}
if (spread > MaxSpread_pips) return(0);
// ギャップフィルター
if(isbuy && Close[0] - Close[1] >= Gap_Pips * xpoint)
return(0); // (現在価格-1本足終値)が、指定pips以上だったら買い禁止
if(!isbuy && Close[1] - Close[0] >= Gap_Pips * xpoint)
return(0); // (1本足終値-現在価格)が、指定pips以上だったら売り禁止
// 年末年始フィルター_12/23~1/3まではエントリーしない
int NGMonth = Month();
int NGDay = Day();
if (YearendClose && ((NGMonth == 12 && NGDay >= 21) || (NGMonth == 1 && NGDay <= 3)))
{
return(0);
}
//エントリーフィルター1ココマデ
return(3);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| エントリーフィルター2 |
//+------------------------------------------------------------------+
int Entry_Filter2(bool isbuy)
{
//エントリーフィルター2
//水曜日制御フィルター
if (TimeDayOfWeek(TimeCurrent()) != 3) return(0);
//エントリーフィルター2ココマデ
return(3);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| エントリーフィルター3 |
//+------------------------------------------------------------------+
int Entry_Filter3(bool isbuy)
{
//エントリーフィルター3
// MAフィルター
double MA1_buy1 = iMA(NULL, MA_TF_buy, MA_period_buy, 0, MODE_SMA, PRICE_CLOSE, 1);
double MA1_buy2 = iMA(NULL, MA_TF_buy, MA_period_buy, 0, MODE_SMA, PRICE_CLOSE, 2);
double StdDev1 = iStdDev(NULL, SD_TF, SD_Period, 0, MODE_SMA, PRICE_CLOSE, 1);
// ローソク足が、移動平均線より下にいて、且つ標準偏差が指定値より大きければトレードしない
if (Filter && MA1_buy2 < MA1_buy1 && StdDev1 > SD_Line)
{
return(0);
} // 買い
//エントリーフィルター3ココマデ
return(3);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| 決済ルール1 |
//+------------------------------------------------------------------+
int Exit_Rule1(bool isbuy)
{
// 決済ルール1
// 時間制御による決済判定
if (isbuy && PositionClose_L1)
{
return(1);
} // 買いを決済
// 決済ルール1ココマデ
return(3);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| チャート自動セット |
//+------------------------------------------------------------------+
// チャートセット初期化
void ChartSet()
{
// 気配値強制表示&自動切替
int chartWidth = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS); // チャート幅の計算
int textWidth = 200;//StringLen(WindowExpertName()) * 12; // 固定値pxまたはテキストの幅の計算
double ShiftPer = textWidth * 100 / chartWidth;
if (!IsTesting())
{
if (StringSubstr(Symbol(), 0, 6) != SYMBOL1 || Period() != Chart_TimeFrame)
{
SymbolSelect(SYMBOL1 + StringSubstr(Symbol(), 6, StringLen(Symbol())), true);
ChartSetSymbolPeriod(0, SYMBOL1 + StringSubstr(Symbol(), 6, StringLen(Symbol())), Chart_TimeFrame);
}
// 現在のシンボルが4文字の場合。無しならコメントアウト
if (StringSubstr(Symbol(), 0, 4) != SYMBOL2 || Period() != Chart_TimeFrame)
{
SymbolSelect(SYMBOL2 + StringSubstr(Symbol(), StringSubstr(Symbol(), 0, 4) == SYMBOL2? 4 : 6, StringLen(Symbol())), true);
ChartSetSymbolPeriod(0, SYMBOL2 + StringSubstr(Symbol(), StringSubstr(Symbol(), 0, 4) == SYMBOL2? 4 : 6, StringLen(Symbol())), Chart_TimeFrame);
}
ChartSetInteger(0, CHART_COLOR_BACKGROUND, clrBlack);
ChartSetInteger(0, CHART_COLOR_FOREGROUND, clrWhite);
ChartSetInteger(0, CHART_COLOR_GRID, clrLightSlateGray);
ChartSetInteger(0, CHART_COLOR_CHART_UP, clrOlive);
ChartSetInteger(0, CHART_COLOR_CHART_DOWN, clrOlive);
ChartSetInteger(0, CHART_COLOR_CANDLE_BULL, clrBlack);
ChartSetInteger(0, CHART_COLOR_CANDLE_BEAR, clrBeige);
ChartSetInteger(0, CHART_COLOR_CHART_LINE, clrOlive);
ChartSetInteger(0, CHART_COLOR_VOLUME, clrOlive);
ChartSetInteger(0, CHART_COLOR_ASK, clrRed);
ChartSetInteger(0, CHART_COLOR_STOP_LEVEL, clrRed);
ChartSetInteger(0, CHART_SHIFT, true);
ChartSetDouble(0, CHART_SHIFT_SIZE, ShiftPer);
ChartSetInteger(0, CHART_AUTOSCROLL, true);
//ChartSetInteger(0, CHART_SHOW_DATE_SCALE, true); // これを入れるとなぜか表示範囲が狭くなる
//ChartSetInteger(0, CHART_SHOW_PRICE_SCALE, true); // これを入れるとなぜか表示範囲が狭くなる
ChartSetInteger(0, CHART_FOREGROUND, false);
ChartSetInteger(0, CHART_SHOW_GRID, false);
ChartSetInteger(0, CHART_SHOW_ONE_CLICK, false);
ChartSetInteger(0, CHART_SHOW_OHLC, false);
ChartSetInteger(0, CHART_SHOW_PERIOD_SEP, true);
ChartSetInteger(0, CHART_SHOW_ASK_LINE, true);
ChartSetInteger(0, CHART_SCALE, 3);
ChartSetInteger(0, CHART_MODE, CHART_CANDLES);
}
}
// 状態によるチャート配色変更
void ChartSet2()
{
color ChartWar1 = ChartWarning? clrDarkGray : clrWhite;
color ChartWar2 = ChartWarning? clrDimGray : clrOlive;
color ChartWar3 = ChartWarning? clrSilver : clrBeige;
if (!IsTesting())
{
ChartSetInteger(0, CHART_COLOR_BACKGROUND, clrBlack);
ChartSetInteger(0, CHART_COLOR_FOREGROUND, ChartWar1);
ChartSetInteger(0, CHART_COLOR_GRID, clrLightSlateGray);
ChartSetInteger(0, CHART_COLOR_CHART_UP, ChartWar2);
ChartSetInteger(0, CHART_COLOR_CHART_DOWN, ChartWar2);
ChartSetInteger(0, CHART_COLOR_CANDLE_BULL, clrBlack);
ChartSetInteger(0, CHART_COLOR_CANDLE_BEAR, ChartWar3);
ChartSetInteger(0, CHART_COLOR_CHART_LINE, ChartWar2);
ChartSetInteger(0, CHART_COLOR_VOLUME, ChartWar2);
ChartSetInteger(0, CHART_COLOR_ASK, clrRed);
ChartSetInteger(0, CHART_COLOR_STOP_LEVEL, clrRed);
}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| チャートの中央にシンボルを描画する |
//+------------------------------------------------------------------+
void CenterSymbol()
{
string TEXT1 = StringSubstr(Symbol(), 0, 6);
string TEXT2 = (Period() == 1? "M1": Period() == 5? "M5": Period() == 15? "M15": Period() == 30? "M30":
Period() == 60? "H1": Period() == 240? "H4": Period() == 1440? "D1": Period() == 10080? "W1": "MN1")
+ "/" + DoubleToStr(MarketInfo(Symbol(),MODE_SPREAD) / 10, 1);
int FontSize = 36;
int chartWidth = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
int chartHeight = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS);
int textWidth = StringLen(TEXT1) * FontSize / 2; // テキストの幅の計算
int textHeight = FontSize; // テキストの高さ
// テキストの中心からの座標を計算
int x = (chartWidth - textWidth) / 2 + textWidth / 2;
int y = (chartHeight - textHeight) / 2 + textHeight / 2;
DrawTextInCenter("Symbol1", TEXT1, x, y - FontSize, FontSize, C'60, 60, 60');
DrawTextInCenter("Symbol2", TEXT2, x, y + FontSize, FontSize, C'60, 60, 60');
}
void DrawTextInCenter(string Symbolname, string label_text, int pos_x, int pos_y, int s, color clr= clrBlack)
{
ObjectCreate(Symbolname, OBJ_LABEL, 0, 0, 0);
ObjectSetString(0, Symbolname, OBJPROP_TEXT, label_text);
ObjectSetInteger(0, Symbolname, OBJPROP_FONTSIZE, s);
ObjectSetString(0, Symbolname, OBJPROP_FONT, "Segoe UI");
ObjectSetInteger(0, Symbolname, OBJPROP_XDISTANCE, pos_x);
ObjectSetInteger(0, Symbolname, OBJPROP_YDISTANCE, pos_y);
ObjectSetInteger(0, Symbolname, OBJPROP_COLOR, clr);
ObjectSetInteger(0, Symbolname, OBJPROP_BACK, true);
ObjectSetInteger(0, Symbolname, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, Symbolname, OBJPROP_ANCHOR, ANCHOR_CENTER);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| チャートコメント表示 |
//+------------------------------------------------------------------+
void ChartComment()
{
if (!IsTradeAllowed() || !IsConnected())
{
ChartWarning = true;
ChartSet2();
}
else
{
ChartWarning = false;
ChartSet2();
}
color clrChartWar = ChartWarning? clrNONE : clrWhite;
color clrChartWarPP = ChartWarning? clrNONE : totalpips < 0? clrOrangeRed : clrWhite;
color clrChartWarPF = ChartWarning? clrNONE : 0 < ProfitFactor && ProfitFactor < 1? clrOrangeRed : clrWhite;
string LotsComment;
if (MM_ON == Fixed) LotsComment = DoubleToStr(Lots,2);
else LotsComment = DoubleToStr(CalculateLots(MM_Risk, StopLoss_pips),2) +
" (" + DoubleToStr(MM_Risk,1) +"%)";
string Comment0 = (string)MagicNumber + " [Magic]";
string Comment1 = LotsComment + " [Lots]";
string Comment2 = (MM_ON == 0 ? "Fixed" : MM_ON == 1 ? "FreeMargin" : "Balance") + " [MM]";
string Comment3 = DoubleToStr(MaxSpread_pips,1) + "/" + DoubleToStr(SpreadAve,1) + " [Spread Lim/Ave]";
//string Comment4 = (Summertime == 0 ? "none" : Summertime == 1 ? "US" : "UK") + " [Summertime]";
string Comment4 = DoubleToStr(TakeProfit_pips, 0) + "/" + DoubleToStr(StopLoss_pips, 0) + " [TP/SL]";
string Comment5 = DoubleToStr(MarketInfo(Symbol(),MODE_SWAPLONG), 2) + "/" +
DoubleToStr(MarketInfo(Symbol(),MODE_SWAPSHORT), 2) + " [Swap B/S]";
string Comment6 = DoubleToStr(TradeCounts, 0) + " [TradeCounts]";
string Comment7 = DoubleToStr(totalpips, 1) + " [Profit (pips)]";
string Comment8 = (plus_profit == 0 || minus_profit == 0? "--- [Profit factor]" :
DoubleToStr(ProfitFactor, 2) + " [Profit factor]");
string Comment9 = (plus_profit == 0 || minus_profit == 0? "---/--- [RRR/Win%]" :
DoubleToStr(RRR, 2) + "/" + DoubleToStr(WinPer, 1) + " [RRR/Win%]");
CommentLabel("ComObj0", Comment0, 4, 18, 10, clrYellow);
CommentLabel("ComObj1", Comment1, 4, 40, 10, clrYellow);
CommentLabel("ComObj2", Comment2, 4, 64, 8, clrChartWar);
CommentLabel("ComObj3", Comment3, 4, 82, 8, clrChartWar);
//CommentLabel("ComObj4", Comment4, 4, 100, 8, clrChartWar);
CommentLabel("ComObj4", Comment4, 4, 100, 8, clrChartWar);
CommentLabel("ComObj5", Comment5, 4, 118, 8, clrChartWar);
CommentLabel("ComObj6", Comment6, 4, 136, 8, clrChartWar);
CommentLabel("ComObj7", Comment7, 4, 154, 8, clrChartWarPP);
CommentLabel("ComObj8", Comment8, 4, 172, 8, clrChartWarPF);
CommentLabel("ComObj9", Comment9, 4, 190, 8, clrChartWar);
}
//+------------------------------------------------------------------+
void CommentLabel(string ComName, string ComText, int ComPos_x, int ComPos_y, int ComSize, color ComClr= clrBlack)
{
ComPos_x = (int)NormalizeDouble(ComPos_x * DPIAdjust, 0); // 別途DPI換算コードで調整
ComPos_y = (int)NormalizeDouble(ComPos_y * DPIAdjust, 0); // 別途DPI換算コードで調整
ObjectCreate(ComName, OBJ_LABEL, 0, 0, 0);
ObjectSetString (0, ComName, OBJPROP_TEXT, ComText);
ObjectSetInteger(0, ComName, OBJPROP_XDISTANCE, ComPos_x);
ObjectSetInteger(0, ComName, OBJPROP_YDISTANCE, ComPos_y);
ObjectSetInteger(0, ComName, OBJPROP_FONTSIZE, ComSize);
ObjectSetInteger(0, ComName, OBJPROP_COLOR, ComClr);
ObjectSetString (0, ComName, OBJPROP_FONT, "Segoe UI");
ObjectSetInteger(0, ComName, OBJPROP_BACK, true);
ObjectSetInteger(0, ComName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, ComName, OBJPROP_CORNER, CORNER_RIGHT_UPPER);
ObjectSetInteger(0, ComName, OBJPROP_ANCHOR, ANCHOR_RIGHT_UPPER);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| チャートにトレード履歴表示 |
//+------------------------------------------------------------------+
void PosHis()
{
int res;
double pips = 0;
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
res = OrderSelect(i, SELECT_BY_POS);
if (OrderSymbol() != Symbol() || OrderType() > 1 || OrderMagicNumber() != MagicNumber)
continue;
pips += trend((string)OrderTicket(), OrderOpenTime(), OrderOpenPrice(), Time[0], OrderType() == 0 ? Bid : Ask, OrderType());
}
}
//+------------------------------------------------------------------+
void history()
{
int res;
totalpips = 0;
plus_profit = 0;
minus_profit = 0;//, ProfitFactor = 0;
minus_count = 0;
plus_count = 0;
TradeCounts = 0;
// トレード履歴を検索
for (int i = OrdersHistoryTotal() - 1; i >= 0; i--)
{
res = OrderSelect(i, SELECT_BY_POS, MODE_HISTORY);
if (OrderSymbol() != Symbol() || OrderType() > 1 || OrderMagicNumber() != MagicNumber)
continue;
// 合計pips計算
totalpips += trend((string)OrderTicket(), OrderOpenTime(), OrderOpenPrice(), OrderCloseTime(), OrderClosePrice(), OrderType());
// プロフィットファクター・RRR・勝率計算
if (OrderProfit() < 0)
{
minus_profit -= OrderProfit();
minus_count += 1;
}
else if (OrderProfit() >= 0)
{
plus_profit += OrderProfit();
plus_count += 1;
}
if (minus_profit != 0 && plus_count != 0 && minus_count != 0)
{
ProfitFactor = plus_profit / minus_profit;
RRR = (plus_profit / plus_count) / (minus_profit / minus_count);
WinPer = (plus_count * 100) / (plus_count + minus_count);
}
TradeCounts = minus_count + plus_count;
}
}
//+------------------------------------------------------------------+
double trend(string obj_name, datetime Time1, double Close1, datetime Time2, double Close2, int type)
{
double pips = (double)DoubleToStr((type == 0 ? Close2 - Close1 : Close1 - Close2) / Point() * 0.1 - tes, 1);
int Shift2 = iBarShift(NULL, 0, Time2);
datetime Timex = iTime(NULL, 0, Shift2 + 1);
// トレード線
ObjectDelete("hislt" + obj_name);
ObjectCreate(0, "hislt" + obj_name, OBJ_TREND, 0, Time1, Close1, Time2, Close2);
ObjectSetInteger(0, "hislt" + obj_name, OBJPROP_COLOR, type == 0 ? clrDodgerBlue : clrOrangeRed);
ObjectSetInteger(0, "hislt" + obj_name, OBJPROP_STYLE, 0);
ObjectSetInteger(0, "hislt" + obj_name, OBJPROP_WIDTH, 2);
ObjectSetInteger(0, "hislt" + obj_name, OBJPROP_SELECTABLE, false); // オブジェクトの選択可否設定
ObjectSetInteger(0, "hislt" + obj_name, OBJPROP_RAY_RIGHT, false); // 右に線を延長
// トレード線内のpips表示
// 文字本体
ObjectDelete("hislx" + obj_name);
ObjectCreate(0, "hislx" + obj_name, OBJ_TEXT, 0, Timex, Close2);
ObjectSetInteger(0, "hislx" + obj_name, OBJPROP_COLOR, pips < 0 ? clrOrangeRed : !IsTesting()? clrLime : clrYellow);//type == 0 ? BuyColor : SellColor);
ObjectSetInteger(0, "hislx" + obj_name, OBJPROP_SELECTABLE, false); // オブジェクトの選択可否設定
ObjectSetInteger(0, "hislx" + obj_name, OBJPROP_FONTSIZE, 12); // フォントサイズ
ObjectSetInteger(0, "hislx" + obj_name, OBJPROP_ANCHOR, ANCHOR_RIGHT); // 描画位置
ObjectSetString(0, "hislx" + obj_name, OBJPROP_TEXT, DoubleToStr(pips, 1)); // 表示するテキスト
ObjectSetString(0, "hislx" + obj_name, OBJPROP_FONT, "Segoe UI Semibold"); // フォント
return(pips);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| スプレッド計測・オートスプレッド |
//+------------------------------------------------------------------+
void MeasureSP()
{
// MT4時間1:00のスプレッド
int Hour1 = TimeHour(TimeCurrent());
int Minute1 = TimeMinute(TimeCurrent());
if (Hour1 == 1 && Minute1 == 0)
{
TickCount++;
SpreadSum += MeasureSpread;
SpreadMin = SpreadMin == 0 ? SpreadMin = MeasureSpread : SpreadMin;
if (TickCount > 0 && SpreadSum > 0) SpreadAve = SpreadSum / TickCount;
if (SpreadMax < MeasureSpread) SpreadMax = MeasureSpread;
if (SpreadMin > MeasureSpread) SpreadMin = MeasureSpread;
}
// 月足のバー更新時に累積値リセット
if (lastBars != iBars(NULL, PERIOD_MN1))
{
lastBars = iBars(NULL, PERIOD_MN1);
SpreadSum = 0;
TickCount = 0;
}
// オートスプレッド計算
Adjustspread = SpreadMin + Adjustspread_Margin; // 平均にマージン加算
MaxSpread_pips = MathMin(Adjustspread, AllowMaxSpread); // 内部設定の最大値とマージン加算を比較し小さい方を採用
}
//+------------------------------------------------------------------+