Remove obsolete refactor artifacts and update specs
This commit is contained in:
@@ -1,935 +0,0 @@
|
||||
//+------------------------------------------------------------------+
|
||||
//| HIT_EA.mq5 |
|
||||
//| Copyright 2026, nanpin-martin.com |
|
||||
//| https://www.nanpin-martin.com |
|
||||
//+------------------------------------------------------------------+
|
||||
#property copyright "Copyright 2026, nanpin-martin.com"
|
||||
#property link "https://nanpin-martin.com/"
|
||||
#property version "1.00"
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| バッチファイル実行用の設定
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
#import "Shell32.dll"
|
||||
int ShellExecuteW(int hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);
|
||||
#import
|
||||
|
||||
// バッチファイルのパス
|
||||
string get_trend_reply_bat = "C:\\ea_py\\get_trend_reply.bat"; // H4: trend
|
||||
string get_entry_reply_bat = "C:\\ea_py\\get_entry_reply.bat"; // H1: entry
|
||||
|
||||
// プロセス完了ファイルの設定
|
||||
string done_trend_file = "process_done_trend.txt";
|
||||
string done_entry_file = "process_done_entry.txt";
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| インプットの設定
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//--- 入力パラメータ
|
||||
input double lot_size = 0.01; // ロット数
|
||||
input double spread_limit = 20; // 許容スプレッド(point)
|
||||
input int magic_number = 10001; // マジックナンバー
|
||||
input int initial_order = 0; // 起動時の注文(0:なし, 1:あり)
|
||||
ulong slippage = 10; // スリッページ
|
||||
|
||||
//--- 主要な定数・設定
|
||||
#define POSITION_LIMIT 48
|
||||
#define ENTRY_H1_LIMIT 1 // H1本数(=1時間)
|
||||
#define CLOSE_H1_LIMIT 12 // H1本数(=12時間)
|
||||
#define HISTORY_BARS 72
|
||||
// ANALYZE_TIMEFRAME は削除(H4/H1 両方使うため定数ではなく直接指定)
|
||||
#define TARGET_SIZE 13
|
||||
#define DEFAULT_TARGET_PRICE 0.0
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| EAの状態をまとめる構造体
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
struct EAState
|
||||
{
|
||||
int trend_state; // ★追加:トレンドを格納する変数
|
||||
int res_chk; // GPTの回答が正しく取得できたか
|
||||
double en_price[5]; // エントリー基準価格
|
||||
double tp_price[5]; // 利益確定価格
|
||||
double sl_price[5]; // ロスカット基準価格
|
||||
bool load_trend_flg; // ★変更:トレンドを更新するタイミングか
|
||||
bool load_target_flg; // ★変更:ターゲット価格を更新するタイミングか
|
||||
int chk_cnt; // エントリー判定の試行回数
|
||||
datetime last_trend_update; // ★追加:前回トレンドを更新した時刻
|
||||
datetime last_target_update; // ★変更:前回ターゲット価格を更新した時刻
|
||||
datetime last_chk;
|
||||
};
|
||||
|
||||
EAState g_ea; // EA全体の状態をここで管理
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 必要な関数プロトタイプ宣言
|
||||
//| プロセス完了ファイル("process_done.txt")関連
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
// "process_done.txt"を作成する関数
|
||||
void CreateDoneFile(const string name);
|
||||
|
||||
// "process_done.txt"を削除する関数
|
||||
void DeleteDoneFile(const string name);
|
||||
|
||||
// "process_done.txt"の存在を確認し、存在する場合はtrueを返す関数
|
||||
bool CheckDoneFile(const string name);
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 必要な関数プロトタイプ宣言
|
||||
//| OHLCデータの取得からターゲット価格の取得まで
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//| 最新のOHLCデータを取得する関数
|
||||
bool GetLatestOHLC(datetime ×[], double &open_prices[], double &high_prices[], double &low_prices[], double &close_prices[], ENUM_TIMEFRAMES tf, int bars_count);
|
||||
|
||||
//| "ohlc.csv"を出力する関数
|
||||
void RecordOHLC(const string filename, const datetime ×[], const double &open_prices[], const double &high_prices[], const double &low_prices[], const double &close_prices[]);
|
||||
|
||||
//| バッチファイル(Pythonスクリプト)を実行する関数
|
||||
void ExecuteBatchTrend();
|
||||
void ExecuteBatchEntry();
|
||||
|
||||
// | "ohlc.csv"を出力後、バッチファイルの実行する関数
|
||||
bool RecordOHLCAndExecuteBatch_Trend(EAState &state);
|
||||
bool RecordOHLCAndExecuteBatch_Entry(EAState &state);
|
||||
|
||||
//| ターゲット価格を取得する関数
|
||||
bool GetTargetPrices(EAState &state);
|
||||
|
||||
//| "target_prices.txt"を読み込む関数
|
||||
void LoadTargetPrices(double &target_prices[]);
|
||||
|
||||
//| "xxx"を読み込む関数
|
||||
bool GetTrendState(EAState &state);
|
||||
void LoadTrendState(int &trend_state);
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 必要な関数プロトタイプ宣言
|
||||
//| エントリー注文関連
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//| エントリー注文を送信する関数 (1:buy-stop, 2:buy-limit, 3:sell-stop, 4:sell-limit)
|
||||
bool SendOrder(int orderType, double price, double tp, double sl);
|
||||
|
||||
//| 注文の執行ポリシーを取得する関数
|
||||
ENUM_ORDER_TYPE_FILLING GetOrderFillingPolicy(string symbol);
|
||||
|
||||
//| 注文コメント(ローカル時刻)を生成する関数(先頭に orderType を付与)
|
||||
string RequestComment(int orderType);
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 必要な関数プロトタイプ宣言
|
||||
//| 時間制限処理関連
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//| 時間が経過したエントリー注文をキャンセルする関数
|
||||
bool CancelExpiredOrders();
|
||||
|
||||
//| 時間が経過したポジションをクローズする関数
|
||||
bool CloseExpiredPositions();
|
||||
|
||||
//| 指定された時間に最も近いバーのインデックスを返す関数
|
||||
// int GetBarIndexByTime(datetime time, int default_index = 0);
|
||||
int GetBarShiftByTime(datetime time, ENUM_TIMEFRAMES tf, int default_shift = -1);
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 起動時の処理
|
||||
//+------------------------------------------------------------------+
|
||||
void OnInit()
|
||||
// プロセス完了ファイル("process_done.txt)"を作成
|
||||
{
|
||||
CreateDoneFile(done_trend_file);
|
||||
CreateDoneFile(done_entry_file);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| ティック毎の処理
|
||||
//+------------------------------------------------------------------+
|
||||
void OnTick()
|
||||
{
|
||||
static int init_order_flg = initial_order;
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
// (1) H4更新検知:トレンド用
|
||||
// ─────────────────────────────────────────────
|
||||
int current_bars_H4 = iBars(NULL, PERIOD_H4);
|
||||
static int pre_bars_H4 = current_bars_H4;
|
||||
int bars_H4_change = current_bars_H4 - pre_bars_H4;
|
||||
|
||||
if(bars_H4_change > 0 || init_order_flg == 1)
|
||||
{
|
||||
RecordOHLCAndExecuteBatch_Trend(g_ea);
|
||||
}
|
||||
pre_bars_H4 = current_bars_H4;
|
||||
|
||||
// trend done待ち(なければ以降をスキップ)
|
||||
if(!CheckDoneFile(done_trend_file))
|
||||
return;
|
||||
|
||||
// トレンド取得
|
||||
GetTrendState(g_ea);
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
// (2) H1更新検知:エントリー用
|
||||
// ─────────────────────────────────────────────
|
||||
static bool bars_H1_check = false;
|
||||
|
||||
int current_bars_H1 = iBars(NULL, PERIOD_H1);
|
||||
static int pre_bars_H1 = current_bars_H1;
|
||||
int bars_H1_change = current_bars_H1 - pre_bars_H1;
|
||||
|
||||
if(bars_H1_change > 0 || init_order_flg == 1)
|
||||
{
|
||||
init_order_flg = 0;
|
||||
bars_H1_check = true;
|
||||
g_ea.chk_cnt = 0;
|
||||
g_ea.last_chk = 0;
|
||||
RecordOHLCAndExecuteBatch_Entry(g_ea);
|
||||
}
|
||||
pre_bars_H1 = current_bars_H1;
|
||||
|
||||
// ── ティック情報・コメント表示 ──
|
||||
MqlTick last_tick;
|
||||
if(!SymbolInfoTick(_Symbol, last_tick))
|
||||
{
|
||||
return;
|
||||
}
|
||||
double Ask = last_tick.ask;
|
||||
double Bid = last_tick.bid;
|
||||
double Spread = MathRound((Ask - Bid) / Point()) * Point();
|
||||
|
||||
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
|
||||
|
||||
string message = StringFormat(
|
||||
" \nAsk: %." + IntegerToString(digits) + "f"
|
||||
"\nBid: %." + IntegerToString(digits) + "f"
|
||||
"\nSpread: %." + IntegerToString(digits) + "f"
|
||||
"\n\nLast Trend Update:\n %s"
|
||||
"\n\nTrend State: %.0f" // ★追加
|
||||
"\n\nLast Target Update:\n %s"
|
||||
"\n\n[T1 Buy Stop ] en: %." + IntegerToString(digits) + "f tp: %." + IntegerToString(digits) + "f sl: %." + IntegerToString(digits) + "f"
|
||||
"\n[T2 Buy Limit] en: %." + IntegerToString(digits) + "f tp: %." + IntegerToString(digits) + "f sl: %." + IntegerToString(digits) + "f"
|
||||
"\n[T3 Sell Stop] en: %." + IntegerToString(digits) + "f tp: %." + IntegerToString(digits) + "f sl: %." + IntegerToString(digits) + "f"
|
||||
"\n[T4 SellLimit] en: %." + IntegerToString(digits) + "f tp: %." + IntegerToString(digits) + "f sl: %." + IntegerToString(digits) + "f\n",
|
||||
Ask, Bid, Spread,
|
||||
TimeToString(g_ea.last_trend_update, TIME_DATE | TIME_MINUTES),
|
||||
g_ea.trend_state, // ★追加
|
||||
TimeToString(g_ea.last_target_update, TIME_DATE | TIME_MINUTES),
|
||||
g_ea.en_price[1], g_ea.tp_price[1], g_ea.sl_price[1],
|
||||
g_ea.en_price[2], g_ea.tp_price[2], g_ea.sl_price[2],
|
||||
g_ea.en_price[3], g_ea.tp_price[3], g_ea.sl_price[3],
|
||||
g_ea.en_price[4], g_ea.tp_price[4], g_ea.sl_price[4]
|
||||
);
|
||||
Comment(message);
|
||||
|
||||
// スプレッド制限
|
||||
if(Spread > spread_limit * Point())
|
||||
return;
|
||||
|
||||
// entry done待ち
|
||||
if(!CheckDoneFile(done_entry_file))
|
||||
return;
|
||||
|
||||
// ターゲット取得
|
||||
GetTargetPrices(g_ea);
|
||||
|
||||
// 期限切れ注文キャンセル・ポジクローズ
|
||||
if(OrdersTotal() > 0)
|
||||
CancelExpiredOrders();
|
||||
if(PositionsTotal() > 0)
|
||||
CloseExpiredPositions();
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
// エントリー条件判定&注文送信(H1更新タイミングで1回)
|
||||
// ─────────────────────────────────────────────
|
||||
// if(bars_H4_check && TimeCurrent() - g_ea.last_chk >= 60)
|
||||
// {
|
||||
// bars_H4_check = false;
|
||||
// g_ea.last_chk = TimeCurrent();
|
||||
if(bars_H1_check && TimeCurrent() - g_ea.last_chk >= 60)
|
||||
{
|
||||
bars_H1_check = false;
|
||||
g_ea.last_chk = TimeCurrent();
|
||||
|
||||
if(g_ea.res_chk == 0)
|
||||
{
|
||||
Print("[Entry Skip] res_chk=0 (range). No entry orders are sent.");
|
||||
g_ea.chk_cnt = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
int used = OrdersTotal() + PositionsTotal();
|
||||
if(used >= POSITION_LIMIT)
|
||||
{
|
||||
Print("Position limit exceeded: used=", used, " limit=", POSITION_LIMIT);
|
||||
}
|
||||
else
|
||||
{
|
||||
int sent_success = 0; // ★ 送信成功数(= SendOrder true の回数)
|
||||
|
||||
// ★ 1..4 を順に判定して、条件OKなら送る
|
||||
for(int t=1; t<=4; t++)
|
||||
{
|
||||
// ポジション上限チェック(途中で到達したら打ち切り)
|
||||
used = OrdersTotal() + PositionsTotal();
|
||||
if(used >= POSITION_LIMIT)
|
||||
{
|
||||
Print("Position limit reached while sending. used=", used, " limit=", POSITION_LIMIT);
|
||||
break;
|
||||
}
|
||||
|
||||
string entry_type;
|
||||
double cur_price; // ログ用(Ask/Bid)
|
||||
|
||||
if(t==1)
|
||||
{
|
||||
entry_type="Buy Stop";
|
||||
cur_price=Ask;
|
||||
}
|
||||
else
|
||||
if(t==2)
|
||||
{
|
||||
entry_type="Buy Limit";
|
||||
cur_price=Ask;
|
||||
}
|
||||
else
|
||||
if(t==3)
|
||||
{
|
||||
entry_type="Sell Stop";
|
||||
cur_price=Bid;
|
||||
}
|
||||
else
|
||||
{
|
||||
entry_type="Sell Limit"; // t==4
|
||||
cur_price=Bid;
|
||||
}
|
||||
|
||||
double en = g_ea.en_price[t];
|
||||
double tp = g_ea.tp_price[t];
|
||||
double sl = g_ea.sl_price[t];
|
||||
|
||||
bool ok=false;
|
||||
|
||||
if(t==1)
|
||||
ok = (Ask < en && tp > en && sl < en); // buy-stop
|
||||
else
|
||||
if(t==2)
|
||||
ok = (Ask > en && tp > en && sl < en); // buy-limit
|
||||
else
|
||||
if(t==3)
|
||||
ok = (Bid > en && tp < en && sl > en); // sell-stop
|
||||
else
|
||||
ok = (Bid < en && tp < en && sl > en); // sell-limit
|
||||
|
||||
if(ok)
|
||||
{
|
||||
Print("[", entry_type, " Order Try at ", cur_price, "] en=", en, " tp=", tp, " sl=", sl);
|
||||
|
||||
if(SendOrder(t, en, tp, sl))
|
||||
{
|
||||
sent_success++;
|
||||
Print("[", entry_type, " Order Sent] ticket ok. en=", en, " tp=", tp, " sl=", sl);
|
||||
}
|
||||
else
|
||||
{
|
||||
Print("[", entry_type, " Order Failed] en=", en, " tp=", tp, " sl=", sl);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Print("[No ", entry_type, "] cur=", cur_price, " en=", en, " tp=", tp, " sl=", sl);
|
||||
}
|
||||
}
|
||||
|
||||
if(sent_success > 0)
|
||||
{
|
||||
g_ea.chk_cnt = 0; // 1件でも通ったら終了
|
||||
}
|
||||
else
|
||||
{
|
||||
g_ea.chk_cnt += 1;
|
||||
Print("[Retry] no order sent. chk_cnt=", g_ea.chk_cnt, "/10");
|
||||
|
||||
if(g_ea.chk_cnt < 10)
|
||||
{
|
||||
// bars_H4_check = true; // 60秒後に再度このブロックに入る
|
||||
bars_H1_check = true; // ★ GPT-EAの bars_H4_check → bars_H1_check に変更
|
||||
}
|
||||
else
|
||||
{
|
||||
Print("[Retry End] reached max tries. reset chk_cnt.");
|
||||
g_ea.chk_cnt = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| "process_done.txt"を作成する関数
|
||||
//+------------------------------------------------------------------+
|
||||
void CreateDoneFile(const string name)
|
||||
{
|
||||
if(!FileIsExist(name))
|
||||
{
|
||||
int h = FileOpen(name, FILE_WRITE|FILE_TXT);
|
||||
if(h != INVALID_HANDLE)
|
||||
FileClose(h);
|
||||
else
|
||||
Print("Failed to create file: ", name, " err=", GetLastError());
|
||||
}
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| "process_done.txt"を削除する関数
|
||||
//+------------------------------------------------------------------+
|
||||
void DeleteDoneFile(const string name)
|
||||
{
|
||||
if(FileIsExist(name))
|
||||
FileDelete(name);
|
||||
}
|
||||
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| "process_done.txt"の存在を確認し、存在する場合はtrueを返す関数
|
||||
//+------------------------------------------------------------------+
|
||||
bool CheckDoneFile(const string name)
|
||||
{
|
||||
return FileIsExist(name);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 最新のOHLCデータを取得する関数
|
||||
//+------------------------------------------------------------------+
|
||||
bool GetLatestOHLC(datetime ×[], double &open_prices[], double &high_prices[], double &low_prices[], double &close_prices[], ENUM_TIMEFRAMES tf, int bars_count)
|
||||
{
|
||||
ArrayResize(times, 0);
|
||||
ArrayResize(open_prices, 0);
|
||||
ArrayResize(high_prices, 0);
|
||||
ArrayResize(low_prices, 0);
|
||||
ArrayResize(close_prices, 0);
|
||||
|
||||
if(bars_count < 2)
|
||||
return false;
|
||||
|
||||
// 時間データを取得
|
||||
if(CopyTime(_Symbol, tf, 0, bars_count, times) <= 0)
|
||||
{
|
||||
Print(__FUNCTION__, ": Failed to copy time data (bars=", bars_count, ") err=", GetLastError());
|
||||
return false;
|
||||
}
|
||||
|
||||
// OHLCデータを取得
|
||||
MqlRates rates[];
|
||||
if(CopyRates(_Symbol, tf, 0, bars_count, rates) <= 0)
|
||||
{
|
||||
Print(__FUNCTION__, ": Failed to copy rates data (bars=", bars_count, ") err=", GetLastError());
|
||||
return false;
|
||||
}
|
||||
|
||||
// 必要なデータを配列に格納
|
||||
for(int i = 0; i < ArraySize(rates); i++)
|
||||
{
|
||||
ArrayResize(open_prices, i + 1);
|
||||
ArrayResize(high_prices, i + 1);
|
||||
ArrayResize(low_prices, i + 1);
|
||||
ArrayResize(close_prices, i + 1);
|
||||
|
||||
open_prices[i] = rates[i].open;
|
||||
high_prices[i] = rates[i].high;
|
||||
low_prices[i] = rates[i].low;
|
||||
close_prices[i] = rates[i].close;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| "ohlc.csv"を出力する関数
|
||||
//+------------------------------------------------------------------+
|
||||
void RecordOHLC(const string filename, const datetime ×[], const double &open_prices[], const double &high_prices[], const double &low_prices[], const double &close_prices[])
|
||||
{
|
||||
// 出力先ファイル名
|
||||
// string filename = "ohlc.csv";
|
||||
|
||||
// ファイルを "書き込みモード" でオープン (テキスト/ANSI)
|
||||
int fileHandle = FileOpen(filename, FILE_WRITE | FILE_TXT | FILE_ANSI);
|
||||
|
||||
// ファイルが開けたかチェック
|
||||
if(fileHandle == INVALID_HANDLE)
|
||||
{
|
||||
Print(__FUNCTION__, " : Failed to open file: ", GetLastError());
|
||||
return;
|
||||
}
|
||||
|
||||
// 配列サイズを取得 (times, open, high, low, close の要素数は同じ前提)
|
||||
int size = ArraySize(times);
|
||||
|
||||
// ヘッダー行を追加
|
||||
FileWrite(fileHandle, "Time,Open,High,Low,Close");
|
||||
|
||||
// 小数点の桁数を取得
|
||||
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
|
||||
|
||||
// フォーマット文字列を動的に生成
|
||||
string formatString = StringFormat("%%s,%%.%df,%%.%df,%%.%df,%%.%df", digits, digits, digits, digits);
|
||||
|
||||
// 1行ずつ "時刻, Open, High, Low, Close" の形式で書き込み
|
||||
for(int i = 0; i < size; i++)
|
||||
{
|
||||
// 時間をフォーマット
|
||||
string timeStr = TimeToString(times[i], TIME_DATE | TIME_MINUTES);
|
||||
|
||||
// 1行分の文字列を生成 (小数点以下の桁数を `digits` に調整)
|
||||
string line = StringFormat(formatString,
|
||||
timeStr, open_prices[i], high_prices[i], low_prices[i], close_prices[i]);
|
||||
|
||||
// ファイルに書き込み (改行付き)
|
||||
FileWrite(fileHandle, line);
|
||||
}
|
||||
|
||||
// 書き込み終了後、ファイルを閉じる
|
||||
FileClose(fileHandle);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| バッチファイル(Pythonスクリプト)を実行する関数
|
||||
//+------------------------------------------------------------------+
|
||||
void ExecuteBatchTrend()
|
||||
{
|
||||
if(CheckDoneFile(done_trend_file))
|
||||
{
|
||||
DeleteDoneFile(done_trend_file);
|
||||
ShellExecuteW(0, "open", get_trend_reply_bat, "", "", 1);
|
||||
}
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| |
|
||||
//+------------------------------------------------------------------+
|
||||
void ExecuteBatchEntry()
|
||||
{
|
||||
if(CheckDoneFile(done_entry_file))
|
||||
{
|
||||
DeleteDoneFile(done_entry_file);
|
||||
ShellExecuteW(0, "open", get_entry_reply_bat, "", "", 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| "ohlc.csv"を出力後、バッチファイルの実行する関数
|
||||
//+------------------------------------------------------------------+
|
||||
bool RecordOHLCAndExecuteBatch_Trend(EAState &state)
|
||||
{
|
||||
datetime times[];
|
||||
double open_prices[], high_prices[], low_prices[], close_prices[];
|
||||
|
||||
if(!GetLatestOHLC(times, open_prices, high_prices, low_prices, close_prices,
|
||||
PERIOD_H4, HISTORY_BARS))
|
||||
{ Print("GetLatestOHLC(H4) failed."); return false; }
|
||||
|
||||
RecordOHLC("ohlc_H4.csv", times, open_prices, high_prices, low_prices, close_prices);
|
||||
ExecuteBatchTrend();
|
||||
|
||||
state.load_trend_flg = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| |
|
||||
//+------------------------------------------------------------------+
|
||||
bool RecordOHLCAndExecuteBatch_Entry(EAState &state)
|
||||
{
|
||||
datetime times[];
|
||||
double open_prices[], high_prices[], low_prices[], close_prices[];
|
||||
|
||||
if(!GetLatestOHLC(times, open_prices, high_prices, low_prices, close_prices,
|
||||
PERIOD_H1, HISTORY_BARS))
|
||||
{ Print("GetLatestOHLC(H1) failed."); return false; }
|
||||
|
||||
RecordOHLC("ohlc_H1.csv", times, open_prices, high_prices, low_prices, close_prices);
|
||||
ExecuteBatchEntry();
|
||||
|
||||
state.load_target_flg = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| |
|
||||
//+------------------------------------------------------------------+
|
||||
bool GetTrendState(EAState &state)
|
||||
{
|
||||
bool ProcessDone = CheckDoneFile(done_trend_file);
|
||||
if(ProcessDone && g_ea.load_trend_flg)
|
||||
{
|
||||
int trend_state;
|
||||
LoadTrendState(trend_state);
|
||||
state.trend_state = trend_state;
|
||||
Print("trend_state: ", state.trend_state);
|
||||
g_ea.load_trend_flg = false;
|
||||
g_ea.last_trend_update = TimeLocal();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| |
|
||||
//+------------------------------------------------------------------+
|
||||
void LoadTrendState(int &trend_state)
|
||||
{
|
||||
string filename = "trend_state.txt";
|
||||
if(FileIsExist(filename))
|
||||
{
|
||||
int filehandle = FileOpen(filename, FILE_READ | FILE_TXT);
|
||||
if(filehandle != INVALID_HANDLE)
|
||||
{
|
||||
string line = FileReadString(filehandle);
|
||||
trend_state = (int)StringToInteger(line);
|
||||
FileClose(filehandle);
|
||||
}
|
||||
else
|
||||
{ Print("Failed to open trend_state.txt"); trend_state = 0; }
|
||||
}
|
||||
else
|
||||
{ Print("trend_state.txt not found"); trend_state = 0; }
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| ターゲット価格を取得する関数
|
||||
//+------------------------------------------------------------------+
|
||||
bool GetTargetPrices(EAState &state)
|
||||
{
|
||||
bool ProcessDone = CheckDoneFile(done_entry_file); // ←変更
|
||||
if(ProcessDone && g_ea.load_target_flg) // ←変更
|
||||
{
|
||||
double target_prices[];
|
||||
LoadTargetPrices(target_prices);
|
||||
|
||||
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
|
||||
|
||||
// 先頭は res_chk
|
||||
state.res_chk = (int)target_prices[0];
|
||||
|
||||
// ★ 1..4 の (en,tp,sl) を読む:合計12個
|
||||
for(int t=1; t<=4; t++)
|
||||
{
|
||||
int base = 1 + (t-1)*3; // 1,4,7,10
|
||||
state.en_price[t] = NormalizeDouble(target_prices[base + 0], digits);
|
||||
state.tp_price[t] = NormalizeDouble(target_prices[base + 1], digits);
|
||||
state.sl_price[t] = NormalizeDouble(target_prices[base + 2], digits);
|
||||
}
|
||||
|
||||
// ログ(任意)
|
||||
Print("target_prices: res=", state.res_chk,
|
||||
" | T1 en=", state.en_price[1], " tp=", state.tp_price[1], " sl=", state.sl_price[1],
|
||||
" | T2 en=", state.en_price[2], " tp=", state.tp_price[2], " sl=", state.sl_price[2],
|
||||
" | T3 en=", state.en_price[3], " tp=", state.tp_price[3], " sl=", state.sl_price[3],
|
||||
" | T4 en=", state.en_price[4], " tp=", state.tp_price[4], " sl=", state.sl_price[4]);
|
||||
|
||||
g_ea.load_target_flg = false; // ←変更
|
||||
g_ea.last_target_update = TimeLocal(); // ←変更
|
||||
}
|
||||
return true;
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
//+------------------------------------------------------------------+
|
||||
//| "target_prices.txt"を読み込む関数
|
||||
//+------------------------------------------------------------------+
|
||||
void LoadTargetPrices(double &target_prices[])
|
||||
{
|
||||
ArrayResize(target_prices, TARGET_SIZE);
|
||||
string filename = "target_prices.txt";
|
||||
|
||||
if(FileIsExist(filename))
|
||||
{
|
||||
int filehandle = FileOpen(filename, FILE_READ | FILE_TXT);
|
||||
if(filehandle != INVALID_HANDLE)
|
||||
{
|
||||
int i = 0;
|
||||
while(!FileIsEnding(filehandle) && i < TARGET_SIZE)
|
||||
{
|
||||
string line = FileReadString(filehandle);
|
||||
target_prices[i] = StringToDouble(line);
|
||||
i++;
|
||||
}
|
||||
FileClose(filehandle);
|
||||
}
|
||||
else
|
||||
{
|
||||
Print("Failed to open file. Error code: ", GetLastError());
|
||||
for(int i = 0; i < TARGET_SIZE; i++)
|
||||
{
|
||||
target_prices[i] = DEFAULT_TARGET_PRICE;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Print("File does not exist: ", filename);
|
||||
for(int i = 0; i < TARGET_SIZE; i++)
|
||||
{
|
||||
target_prices[i] = DEFAULT_TARGET_PRICE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| エントリー注文を送信する関数 (1:buy-stop, 2:buy-limit, 3:sell-stop, 4:sell-limit)
|
||||
//+------------------------------------------------------------------+
|
||||
bool SendOrder(int orderType, double price, double tp, double sl)
|
||||
{
|
||||
MqlTradeRequest request = {};
|
||||
MqlTradeResult result = {};
|
||||
|
||||
request.magic = magic_number;
|
||||
request.symbol = _Symbol;
|
||||
request.volume = lot_size;
|
||||
request.deviation = slippage;
|
||||
request.type_filling = GetOrderFillingPolicy(_Symbol);
|
||||
request.price = NormalizeDouble(price, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
|
||||
request.tp = NormalizeDouble(tp, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
|
||||
request.sl = NormalizeDouble(sl, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
|
||||
request.comment = RequestComment(orderType);
|
||||
|
||||
string orderTypeStr = "";
|
||||
|
||||
// 指値または逆指値注文
|
||||
request.action = TRADE_ACTION_PENDING;
|
||||
|
||||
switch(orderType)
|
||||
{
|
||||
case 1: // 順張り買い (buy-stop)
|
||||
request.type = ORDER_TYPE_BUY_STOP;
|
||||
orderTypeStr = "buy-stop";
|
||||
break;
|
||||
|
||||
case 2: // 逆張り買い (buy-limit)
|
||||
request.type = ORDER_TYPE_BUY_LIMIT;
|
||||
orderTypeStr = "buy-limit";
|
||||
break;
|
||||
|
||||
case 3: // 順張り売り (sell-stop)
|
||||
request.type = ORDER_TYPE_SELL_STOP;
|
||||
orderTypeStr = "sell-stop";
|
||||
break;
|
||||
|
||||
case 4: // 逆張り売り (sell-limit)
|
||||
request.type = ORDER_TYPE_SELL_LIMIT;
|
||||
orderTypeStr = "sell-limit";
|
||||
break;
|
||||
|
||||
default: // 不正なorderType
|
||||
Print(__FUNCTION__, ": invalid orderType=", orderType);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 注文送信
|
||||
if(!OrderSend(request, result))
|
||||
{
|
||||
Print(__FUNCTION__, ": OrderSend failed. err=", GetLastError());
|
||||
return false;
|
||||
}
|
||||
|
||||
// 注文成功確認
|
||||
if(result.retcode == TRADE_RETCODE_PLACED ||
|
||||
result.retcode == TRADE_RETCODE_DONE ||
|
||||
result.retcode == TRADE_RETCODE_DONE_PARTIAL)
|
||||
{
|
||||
Print(request.comment + " - " + orderTypeStr + " order success (ticket=", result.order, ")");
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Print(__FUNCTION__, ": OrderSend retcode=", result.retcode);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 注文の執行ポリシーを取得する関数
|
||||
//+------------------------------------------------------------------+
|
||||
ENUM_ORDER_TYPE_FILLING GetOrderFillingPolicy(string symbol)
|
||||
{
|
||||
long fill_mode = SymbolInfoInteger(symbol, SYMBOL_FILLING_MODE);
|
||||
if((fill_mode & SYMBOL_FILLING_IOC) != 0)
|
||||
return ORDER_FILLING_IOC;
|
||||
if((fill_mode & SYMBOL_FILLING_FOK) != 0)
|
||||
return ORDER_FILLING_FOK;
|
||||
return ORDER_FILLING_RETURN;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 注文コメント(ローカル時刻)を生成する関数(先頭に orderType を付与)
|
||||
//+------------------------------------------------------------------+
|
||||
string RequestComment(int orderType)
|
||||
{
|
||||
datetime localTime = TimeLocal();
|
||||
string timeStr = TimeToString(localTime, TIME_DATE|TIME_MINUTES);
|
||||
|
||||
// 先頭に 1,2,3,4 を付ける(例: "1 | PC Time: 2026.02.14 19:05")
|
||||
return IntegerToString(orderType) + " | PC Time: " + timeStr;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 時間が経過したエントリー注文をキャンセルする関数
|
||||
//+------------------------------------------------------------------+
|
||||
bool CancelExpiredOrders()
|
||||
{
|
||||
bool result = false;
|
||||
|
||||
// 未決済注文の数を取得
|
||||
for(int i = OrdersTotal() - 1; i >= 0; i--)
|
||||
{
|
||||
ulong ticket = OrderGetTicket(i);
|
||||
if(OrderSelect(ticket)) // 注文を選択
|
||||
{
|
||||
if(OrderGetString(ORDER_SYMBOL) != _Symbol)
|
||||
continue;
|
||||
if(OrderGetInteger(ORDER_MAGIC) != magic_number)
|
||||
continue;
|
||||
|
||||
datetime open_time = (datetime)OrderGetInteger(ORDER_TIME_SETUP);
|
||||
|
||||
int open_shift = GetBarShiftByTime(open_time, PERIOD_H1, -1); // H1
|
||||
if(open_shift < 0)
|
||||
continue; // 時刻解決できないなら触らない
|
||||
|
||||
if(open_shift >= ENTRY_H1_LIMIT) // H1本数(=1本 ≒ 1時間)
|
||||
{
|
||||
MqlTradeRequest request = {};
|
||||
MqlTradeResult trade_result = {};
|
||||
request.action=TRADE_ACTION_REMOVE; // 取引操作タイプ
|
||||
request.order = ticket; // 注文チケット
|
||||
if(!OrderSend(request, trade_result)) // 削除リクエスト送信
|
||||
{
|
||||
Print("Failed to delete order. Ticket: ", ticket, " Error: ", GetLastError());
|
||||
}
|
||||
else
|
||||
{
|
||||
if(trade_result.retcode == TRADE_RETCODE_DONE)
|
||||
{
|
||||
Print("Order canceled successfully due to a time limit. Ticket: ", ticket);
|
||||
result = true; // 削除成功フラグ
|
||||
}
|
||||
else
|
||||
{
|
||||
Print("Order cancellation failed. Ticket: ", ticket, " Retcode: ", trade_result.retcode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 時間が経過したポジションをクローズする関数
|
||||
//+------------------------------------------------------------------+
|
||||
bool CloseExpiredPositions()
|
||||
{
|
||||
bool result = false;
|
||||
|
||||
// ポジションを逆順でループ
|
||||
for(int i = PositionsTotal() - 1; i >= 0; i--)
|
||||
{
|
||||
string position_symbol = PositionGetSymbol(i);
|
||||
if(position_symbol!="")
|
||||
{
|
||||
// Magic Number とシンボルでフィルタリング
|
||||
if(position_symbol != _Symbol)
|
||||
continue;
|
||||
if(PositionGetInteger(POSITION_MAGIC) == magic_number)
|
||||
{
|
||||
// ポジションのエントリー時刻を取得
|
||||
datetime entry_time = (datetime)PositionGetInteger(POSITION_TIME);
|
||||
|
||||
int entry_shift = GetBarShiftByTime(entry_time, PERIOD_H1, -1);
|
||||
if(entry_shift < 0)
|
||||
continue;
|
||||
|
||||
if(entry_shift >= CLOSE_H1_LIMIT) // H1本数(=12本 ≒ 12時間)
|
||||
{
|
||||
MqlTradeRequest request = {};
|
||||
MqlTradeResult trade_result = {};
|
||||
|
||||
// ポジションタイプに応じてリクエストを設定
|
||||
int position_type = (int)PositionGetInteger(POSITION_TYPE);
|
||||
request.action = TRADE_ACTION_DEAL;
|
||||
request.position = PositionGetInteger(POSITION_TICKET); // ポジションのチケット番号
|
||||
request.symbol = position_symbol; // シンボル
|
||||
request.volume = PositionGetDouble(POSITION_VOLUME); // ポジションサイズ
|
||||
request.price = (position_type == POSITION_TYPE_BUY)
|
||||
? SymbolInfoDouble(position_symbol, SYMBOL_BID) // BUYの場合はBIDでクローズ
|
||||
: SymbolInfoDouble(position_symbol, SYMBOL_ASK); // SELLの場合はASKでクローズ
|
||||
request.deviation = slippage;
|
||||
request.type = (position_type == POSITION_TYPE_BUY)
|
||||
? ORDER_TYPE_SELL // BUYポジションをSELLでクローズ
|
||||
: ORDER_TYPE_BUY; // SELLポジションをBUYでクローズ
|
||||
request.type_filling = GetOrderFillingPolicy(position_symbol); // 注文執行ポリシー
|
||||
request.magic = magic_number;
|
||||
|
||||
// 注文送信
|
||||
if(!OrderSend(request, trade_result))
|
||||
{
|
||||
Print("Failed to close position. Ticket: ", request.position, " Error: ", GetLastError());
|
||||
continue;
|
||||
}
|
||||
|
||||
// 結果の確認
|
||||
if(trade_result.retcode == TRADE_RETCODE_DONE || trade_result.retcode == TRADE_RETCODE_DONE_PARTIAL)
|
||||
{
|
||||
Print("Position closed successfully due to a time limit. Ticket: ", request.position);
|
||||
result = true; // 少なくとも1つ成功した場合
|
||||
}
|
||||
else
|
||||
{
|
||||
Print("Failed to close position. Ticket: ", request.position, " Retcode: ", trade_result.retcode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Print("Failed to select position at index ", i, ". Error: ", GetLastError());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 指定された時間に最も近いバーのインデックスを返す関数
|
||||
//+------------------------------------------------------------------+
|
||||
int GetBarShiftByTime(datetime time, ENUM_TIMEFRAMES tf, int default_shift = -1)
|
||||
{
|
||||
if(time <= 0)
|
||||
return default_shift;
|
||||
int shift = iBarShift(_Symbol, tf, time, false); // 近傍バーで解決する
|
||||
if(shift < 0)
|
||||
return default_shift;
|
||||
return shift;
|
||||
}
|
||||
//+------------------------------------------------------------------+
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,477 +0,0 @@
|
||||
//+------------------------------------------------------------------+
|
||||
//| HIT_EA.mq5 |
|
||||
//| Copyright 2026, nanpin-martin.com |
|
||||
//| https://www.nanpin-martin.com |
|
||||
//+------------------------------------------------------------------+
|
||||
#property copyright "Copyright 2026, nanpin-martin.com"
|
||||
#property link "https://nanpin-martin.com/"
|
||||
#property version "1.01"
|
||||
|
||||
#include <MyLib/Trading/SLTPManager.mqh>
|
||||
#include <MyLib/Panel/SLTPManagerPanel.mqh>
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| バッチファイル実行用の設定
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
// Windowsプロセス起動・終了確認用
|
||||
#define CREATE_NO_WINDOW 0x08000000
|
||||
#define PROCESS_QUERY_LIMITED_INFORMATION 0x00001000
|
||||
#define SYNCHRONIZE 0x00100000
|
||||
#define WAIT_OBJECT_0 0
|
||||
#define WAIT_TIMEOUT 258
|
||||
#define STILL_ACTIVE 259
|
||||
#define TASKKILL_WAIT_MILLISECONDS 5000
|
||||
|
||||
struct STARTUPINFO_W
|
||||
{
|
||||
uint cb;
|
||||
string lpReserved;
|
||||
string lpDesktop;
|
||||
string lpTitle;
|
||||
uint dwX;
|
||||
uint dwY;
|
||||
uint dwXSize;
|
||||
uint dwYSize;
|
||||
uint dwXCountChars;
|
||||
uint dwYCountChars;
|
||||
uint dwFillAttribute;
|
||||
uint dwFlags;
|
||||
ushort wShowWindow;
|
||||
ushort cbReserved2;
|
||||
long lpReserved2;
|
||||
long hStdInput;
|
||||
long hStdOutput;
|
||||
long hStdError;
|
||||
};
|
||||
|
||||
struct PROCESS_INFORMATION
|
||||
{
|
||||
long hProcess;
|
||||
long hThread;
|
||||
uint dwProcessId;
|
||||
uint dwThreadId;
|
||||
};
|
||||
|
||||
#import "kernel32.dll"
|
||||
int CreateProcessW(string lpApplicationName, string lpCommandLine, long lpProcessAttributes, long lpThreadAttributes, int bInheritHandles, uint dwCreationFlags, long lpEnvironment, string lpCurrentDirectory, STARTUPINFO_W &lpStartupInfo, PROCESS_INFORMATION &lpProcessInformation);
|
||||
int WaitForSingleObject(long hHandle, uint dwMilliseconds);
|
||||
int GetExitCodeProcess(long hProcess, uint &lpExitCode);
|
||||
int CloseHandle(long hObject);
|
||||
long OpenProcess(uint dwDesiredAccess, int bInheritHandle, uint dwProcessId);
|
||||
#import
|
||||
|
||||
// バッチファイルのパス
|
||||
string get_trend_reply_bat = "C:\\ea_py\\bat\\get_trend_reply.bat"; // H4: trend
|
||||
string get_entry_reply_bat = "C:\\ea_py\\bat\\get_entry_reply.bat"; // H1: entry
|
||||
string mt5_file_prefix = ""; // Python linkage file namespace
|
||||
|
||||
// プロセス完了ファイルの設定
|
||||
string done_trend_file = "process_done_trend.txt";
|
||||
string done_entry_file = "process_done_entry.txt";
|
||||
|
||||
// Python出力ファイル
|
||||
string ohlc_h4_file = "ohlc_H4.csv";
|
||||
string ohlc_h1_file = "ohlc_H1.csv";
|
||||
string trend_state_file = "trend_state.txt";
|
||||
string target_prices_file = "target_prices.txt";
|
||||
string target_zones_file = "target_zones.txt";
|
||||
|
||||
// Python実行中を判定するための管理ファイル
|
||||
string running_trend_file = "process_running_trend.txt";
|
||||
string running_entry_file = "process_running_entry.txt";
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| インプットの設定
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
enum SplitLotMode
|
||||
{
|
||||
SPLIT_LOT_TOTAL = 0, // Split total volume into N orders
|
||||
SPLIT_LOT_FIXED = 1 // Use fixed volume per split order
|
||||
};
|
||||
|
||||
//--- 入力パラメータ
|
||||
input double lot_size = 0.01; // ロット数
|
||||
input double spread_limit = 60; // 許容スプレッド(point)
|
||||
input int magic_number = 10001; // マジックナンバー
|
||||
input int initial_order = 0; // 起動時の注文(0:なし, 1:あり)
|
||||
input int input_position_limit = 48; // 自EAの未約定注文+ポジション上限
|
||||
input bool use_split_entry_zone = false; // H1予測ゾーンで分割エントリーする
|
||||
input int split_entry_count = 3; // 分割エントリー本数(1..10)
|
||||
input SplitLotMode split_lot_mode = SPLIT_LOT_TOTAL; // 分割ロット配分モード
|
||||
input double split_total_lot_size = 0.09; // 総量分割モードの合計ロット
|
||||
input double split_fixed_lot_size = 0.01; // 固定ロットモードの1注文ロット
|
||||
input bool cancel_old_split_pending_on_new_zone = true; // 新ゾーン読込時に旧分割pendingを取消
|
||||
input int input_cancel_retry_cooldown_seconds = 60; // pending取消失敗時のticket単位再試行間隔
|
||||
input bool use_m15_entry_filter = true; // M15確定足で発注タイミングを確認
|
||||
input double m15_entry_zone_atr_multiplier = 1.50; // M15平均レンジ何本分まで候補価格への接近を許可
|
||||
input bool use_m15_imbalance_confirmation = true; // T1/T3でM15初動確認を追加
|
||||
input int m15_imbalance_avg_body_period = 20; // M15平均実体計算期間
|
||||
input double m15_imbalance_sensitivity = 2.0; // M15初動検知感度
|
||||
input double m15_imbalance_min_avg_body_points = 1.0; // 平均実体の最小値(point)
|
||||
input bool use_m15_imbalance_debug_log = false; // M15初動確認ログ
|
||||
input int input_entry_max_candidate_age_minutes = 45; // H1候補価格を新規発注に使う最大経過分数
|
||||
input bool input_sltp_manager_enabled = false; // UI連動SLTP管理を有効化
|
||||
input bool input_sltp_show_panel = true; // SLTP操作パネルを表示
|
||||
input bool input_sltp_use_breakeven = false; // 通常ブレークイーブンを有効化
|
||||
input double input_sltp_breakeven_trigger_pips = 30.0; // 通常BE開始pips
|
||||
input double input_sltp_breakeven_buffer_pips = 3.0; // 通常BE固定バッファpips
|
||||
input bool input_sltp_use_elapsed_breakeven = false; // 保有時間BEを有効化
|
||||
input double input_sltp_elapsed_breakeven_hours = 4.0; // 保有時間BE開始時間
|
||||
input double input_sltp_elapsed_breakeven_buffer_pips = 3.0; // 保有時間BE固定バッファpips
|
||||
input bool input_sltp_use_active_trailing = false; // アクティブトレーリングを有効化
|
||||
input double input_sltp_active_breakeven_pips = 30.0; // アクティブ開始pips
|
||||
input double input_sltp_active_stop_loss_offset_pips = 5.0; // 初期固定pips
|
||||
input double input_sltp_active_step_trigger_pips = 10.0; // ステップ更新間隔pips
|
||||
input double input_sltp_active_step_move_pips = 5.0; // 1ステップ固定追加pips
|
||||
input bool input_sltp_use_tp_progress_stop = false; // TP進捗SLを有効化
|
||||
input double input_sltp_tp_progress_trigger_percent = 70.0; // TP進捗SL開始率
|
||||
input double input_sltp_tp_progress_sl_lock_percent = 30.0; // TP距離固定率
|
||||
input bool input_sltp_use_high_volatility_limit = false; // 急変時SL引き締めを有効化
|
||||
ulong slippage = 10; // スリッページ
|
||||
|
||||
//--- 主要な定数・設定
|
||||
#define POSITION_LIMIT 48
|
||||
#define ENTRY_H1_LIMIT 1 // H1本数(=1時間)
|
||||
#define CLOSE_H1_LIMIT 12 // H1本数(=12時間)
|
||||
#define HISTORY_BARS 72
|
||||
#define OHLC_START_SHIFT 1 // 1: 確定足のみをPythonへ渡す
|
||||
#define M15_CONFIRM_BARS 30
|
||||
#define M15_MIN_ENTRY_ZONE_POINTS 10
|
||||
#define M15_MIN_BODY_RATIO 0.25
|
||||
#define M15_REJECTION_WICK_RATIO 0.35
|
||||
#define ENTRY_RETRY_SECONDS 60
|
||||
#define ENTRY_RETRY_LIMIT 10
|
||||
// ANALYZE_TIMEFRAME は削除(H4/H1 両方使うため定数ではなく直接指定)
|
||||
#define TARGET_SIZE 13
|
||||
#define TARGET_ZONE_SCHEMA_VERSION 2
|
||||
#define DEFAULT_TARGET_PRICE 0.0
|
||||
#define PYTHON_TIMEOUT_SECONDS 600 // Python完了待ちの上限(秒)
|
||||
|
||||
#define MARKET_LOW_VOL_RANGE 0
|
||||
#define MARKET_HIGH_VOL_RANGE 1
|
||||
#define MARKET_LOW_VOL_UP 2
|
||||
#define MARKET_HIGH_VOL_UP 3
|
||||
#define MARKET_LOW_VOL_DOWN 4
|
||||
#define MARKET_HIGH_VOL_DOWN 5
|
||||
#define MARKET_TECHNICAL_ERROR_STOP 6
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| EAの状態をまとめる構造体
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
struct EAState
|
||||
{
|
||||
int trend_state; // H4 market_state(0..5、6は技術エラー停止)を格納する変数
|
||||
int res_chk; // GPTの回答が正しく取得できたか
|
||||
double en_price[5]; // エントリー基準価格
|
||||
double tp_price[5]; // 利益確定価格
|
||||
double sl_price[5]; // ロスカット基準価格
|
||||
int zone_res_chk; // 予測ゾーンが正しく取得できたか
|
||||
string zone_candidate_id; // H1確定足由来の候補ID
|
||||
double zone_low[5]; // 分割エントリー用ゾーン下限
|
||||
double zone_high[5]; // 分割エントリー用ゾーン上限
|
||||
double zone_tp[5]; // 分割エントリー用TP
|
||||
double zone_sl[5]; // 分割エントリー用SL
|
||||
bool load_trend_flg; // ★変更:トレンドを更新するタイミングか
|
||||
bool load_target_flg; // ★変更:ターゲット価格を更新するタイミングか
|
||||
int chk_cnt; // エントリー判定の試行回数
|
||||
datetime last_trend_update; // ★追加:前回トレンドを更新した時刻
|
||||
datetime last_target_update; // ★変更:前回ターゲット価格を更新した時刻
|
||||
datetime target_loaded_at; // H1候補価格をEAへ読み込んだサーバー時刻
|
||||
datetime target_candidate_at; // H1候補価格の元になった確定足時刻
|
||||
datetime last_chk;
|
||||
};
|
||||
|
||||
EAState g_ea; // EA全体の状態をここで管理
|
||||
|
||||
// initial_order 用の初回処理フラグ
|
||||
// H4トレンド処理とH1エントリー処理で別々に管理し、初回起動時の再実行ループを防ぐ。
|
||||
bool g_init_trend_pending = false;
|
||||
bool g_init_entry_pending = false;
|
||||
|
||||
// H4/H1のバー更新状態
|
||||
int g_pre_bars_H4 = 0;
|
||||
int g_pre_bars_H1 = 0;
|
||||
int g_pre_bars_M15 = 0;
|
||||
bool g_bars_H1_check = false;
|
||||
bool g_bars_M15_check = false;
|
||||
|
||||
// Prevent repeated cancel requests for the same pending ticket.
|
||||
ulong g_cancel_retry_tickets[];
|
||||
datetime g_cancel_retry_at[];
|
||||
|
||||
// ティックごとの価格情報
|
||||
struct TickContext
|
||||
{
|
||||
double ask;
|
||||
double bid;
|
||||
double spread;
|
||||
double spread_points;
|
||||
int digits;
|
||||
};
|
||||
|
||||
// 外部Pythonプロセスの状態
|
||||
struct ExternalProcessState
|
||||
{
|
||||
long handle;
|
||||
uint process_id;
|
||||
bool active;
|
||||
bool exit_code_ready;
|
||||
uint exit_code;
|
||||
datetime started_at;
|
||||
};
|
||||
|
||||
ExternalProcessState g_trend_process;
|
||||
ExternalProcessState g_entry_process;
|
||||
|
||||
CSLTPManager g_sltp_manager;
|
||||
CSLTPManagerPanel g_sltp_panel;
|
||||
SLTPManagerPanelSettings g_sltp_settings;
|
||||
bool g_sltp_settings_valid = false;
|
||||
bool g_sltp_panel_created = false;
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 起動時の処理
|
||||
//+------------------------------------------------------------------+
|
||||
/**
|
||||
* @brief EA起動時の初期化処理を行います。
|
||||
*
|
||||
* Python連携用のdone/runningファイル状態を確認し、`initial_order` が有効な場合は
|
||||
* H4トレンド判定とH1エントリー価格生成をそれぞれ初回実行対象にします。
|
||||
* H4/H1の初回フラグを分けることで、起動直後にH4処理だけが繰り返される状態を防ぎます。
|
||||
*/
|
||||
int OnInit()
|
||||
// プロセス完了ファイルと実行中ファイルの状態を初期化
|
||||
{
|
||||
PrepareDoneFileOnInit(done_trend_file, running_trend_file, "trend");
|
||||
PrepareDoneFileOnInit(done_entry_file, running_entry_file, "entry");
|
||||
|
||||
// initial_order=1 の場合でも、H4/H1を別々に1回だけ初回実行する。
|
||||
g_init_trend_pending = (initial_order == 1);
|
||||
g_init_entry_pending = (initial_order == 1);
|
||||
g_ea.zone_res_chk = 0;
|
||||
g_ea.zone_candidate_id = "0";
|
||||
g_ea.target_candidate_at = 0;
|
||||
ArrayResize(g_cancel_retry_tickets, 0);
|
||||
ArrayResize(g_cancel_retry_at, 0);
|
||||
|
||||
if(!InitializeSLTPManager())
|
||||
return INIT_FAILED;
|
||||
|
||||
return INIT_SUCCEEDED;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 終了時の処理
|
||||
//+------------------------------------------------------------------+
|
||||
void OnDeinit(const int reason)
|
||||
{
|
||||
ResetExternalProcessState(g_trend_process);
|
||||
ResetExternalProcessState(g_entry_process);
|
||||
|
||||
if(g_sltp_panel_created)
|
||||
g_sltp_panel.Destroy(reason);
|
||||
|
||||
// Clear chart status text left by Comment() when the EA is removed.
|
||||
Comment("");
|
||||
ChartRedraw(0);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| ティック毎の処理
|
||||
//+------------------------------------------------------------------+
|
||||
/**
|
||||
* @brief ティック受信ごとにEA全体の処理を制御します。
|
||||
*
|
||||
* 処理順序は、ティック情報取得、期限切れ注文/ポジション管理、H4トレンド更新、
|
||||
* H1エントリー価格更新、M15エントリータイミング更新、ステータス表示、新規注文判定の順です。
|
||||
* 時間制限処理はPython完了待ちやスプレッド判定より前に実行します。
|
||||
*/
|
||||
void OnTick()
|
||||
{
|
||||
TickContext ctx;
|
||||
if(!GetTickContext(ctx))
|
||||
return;
|
||||
|
||||
// 期限切れ注文・ポジションは、Python待ちやスプレッド制限に関係なく先に処理する。
|
||||
ManageExpiredTrades();
|
||||
|
||||
// Existing-position protection stays active even while Python results are pending.
|
||||
ManageSLTPPositions();
|
||||
|
||||
// 外部Pythonがdoneを返さない場合に、一定時間で待機状態を解除して再実行対象にする。
|
||||
RecoverTimedOutPythonProcesses();
|
||||
|
||||
// H4新バーまたは初回起動時に、トレンド判定用Pythonを起動する。
|
||||
ProcessTrendUpdate(g_ea);
|
||||
|
||||
// トレンド判定が完了していない場合、新規注文側の処理だけをスキップする。
|
||||
if(!IsTrendResultReady())
|
||||
return;
|
||||
|
||||
RefreshTrendState(g_ea);
|
||||
|
||||
// H1新バーまたは初回起動時に、エントリー価格生成用Pythonを起動する。
|
||||
ProcessEntryUpdate(g_ea);
|
||||
|
||||
// M15確定足ごとに、H1候補価格を発注してよいタイミングか再判定する。
|
||||
ProcessM15EntryTimingUpdate();
|
||||
|
||||
UpdateStatusComment(ctx);
|
||||
|
||||
// ここから下は新規注文に関する処理。
|
||||
if(!IsSpreadAllowed(ctx))
|
||||
return;
|
||||
|
||||
if(!IsEntryResultReady())
|
||||
return;
|
||||
|
||||
RefreshTargetPrices(g_ea);
|
||||
ProcessEntryDecisionIfNeeded(g_ea, ctx);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| SLTP manager panel and settings bridge
|
||||
//+------------------------------------------------------------------+
|
||||
string SLTPBoolText(const bool value)
|
||||
{
|
||||
return value ? "ON" : "OFF";
|
||||
}
|
||||
|
||||
void LoadSLTPInputSettings(SLTPManagerPanelSettings &settings)
|
||||
{
|
||||
settings.manager_enabled = input_sltp_manager_enabled;
|
||||
|
||||
settings.use_breakeven = input_sltp_use_breakeven;
|
||||
settings.breakeven_trigger_pips = input_sltp_breakeven_trigger_pips;
|
||||
settings.breakeven_buffer_pips = input_sltp_breakeven_buffer_pips;
|
||||
|
||||
settings.use_elapsed_breakeven = input_sltp_use_elapsed_breakeven;
|
||||
settings.elapsed_breakeven_hours = input_sltp_elapsed_breakeven_hours;
|
||||
settings.elapsed_breakeven_buffer_pips = input_sltp_elapsed_breakeven_buffer_pips;
|
||||
|
||||
settings.use_active_trailing = input_sltp_use_active_trailing;
|
||||
settings.active_breakeven_pips = input_sltp_active_breakeven_pips;
|
||||
settings.active_stop_loss_offset_pips = input_sltp_active_stop_loss_offset_pips;
|
||||
settings.active_step_trigger_pips = input_sltp_active_step_trigger_pips;
|
||||
settings.active_step_move_pips = input_sltp_active_step_move_pips;
|
||||
|
||||
settings.use_tp_progress_stop = input_sltp_use_tp_progress_stop;
|
||||
settings.tp_progress_trigger_percent = input_sltp_tp_progress_trigger_percent;
|
||||
settings.tp_progress_sl_lock_percent = input_sltp_tp_progress_sl_lock_percent;
|
||||
|
||||
settings.use_high_volatility_limit = input_sltp_use_high_volatility_limit;
|
||||
}
|
||||
|
||||
bool ApplySLTPSettings(const SLTPManagerPanelSettings &settings,
|
||||
const bool print_summary)
|
||||
{
|
||||
g_sltp_settings_valid = false;
|
||||
|
||||
g_sltp_manager.SetMagicNumber((ulong)magic_number);
|
||||
g_sltp_manager.SetSymbol(_Symbol);
|
||||
g_sltp_manager.SetDeviationInPoints(slippage);
|
||||
g_sltp_manager.SetBreakevenSettings(settings.use_breakeven,
|
||||
settings.breakeven_trigger_pips,
|
||||
settings.breakeven_buffer_pips);
|
||||
g_sltp_manager.SetElapsedBreakevenSettings(settings.use_elapsed_breakeven,
|
||||
settings.elapsed_breakeven_hours,
|
||||
settings.elapsed_breakeven_buffer_pips);
|
||||
g_sltp_manager.SetActiveTrailingSettings(settings.use_active_trailing,
|
||||
settings.active_breakeven_pips,
|
||||
settings.active_stop_loss_offset_pips,
|
||||
settings.active_step_trigger_pips,
|
||||
settings.active_step_move_pips);
|
||||
g_sltp_manager.SetTpProgressStopSettings(settings.use_tp_progress_stop,
|
||||
settings.tp_progress_trigger_percent,
|
||||
settings.tp_progress_sl_lock_percent);
|
||||
g_sltp_manager.SetHighVolatilityLimitSettings(settings.use_high_volatility_limit);
|
||||
|
||||
if(!g_sltp_manager.ValidateSettings())
|
||||
{
|
||||
Print("HIT SLTP settings rejected. Manager is disabled until valid settings are applied.");
|
||||
return false;
|
||||
}
|
||||
|
||||
g_sltp_settings = settings;
|
||||
g_sltp_settings_valid = true;
|
||||
|
||||
if(print_summary)
|
||||
{
|
||||
Print("HIT SLTP settings: Manager=", SLTPBoolText(settings.manager_enabled),
|
||||
" BE=", SLTPBoolText(settings.use_breakeven),
|
||||
" ElapsedBE=", SLTPBoolText(settings.use_elapsed_breakeven),
|
||||
" ActiveTrail=", SLTPBoolText(settings.use_active_trailing),
|
||||
" TPProgress=", SLTPBoolText(settings.use_tp_progress_stop),
|
||||
" HighVol=", SLTPBoolText(settings.use_high_volatility_limit));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool InitializeSLTPManager()
|
||||
{
|
||||
SLTPManagerPanelSettings initial_settings;
|
||||
LoadSLTPInputSettings(initial_settings);
|
||||
|
||||
if(!ApplySLTPSettings(initial_settings, true))
|
||||
return false;
|
||||
|
||||
g_sltp_panel.Init(g_sltp_settings);
|
||||
if(input_sltp_show_panel)
|
||||
{
|
||||
if(!g_sltp_panel.CreatePanel())
|
||||
{
|
||||
Print("HIT SLTP panel is unavailable. EA continues with input-based SLTP settings.");
|
||||
return true;
|
||||
}
|
||||
|
||||
g_sltp_panel.SetInitialValues();
|
||||
g_sltp_panel_created = true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ManageSLTPPositions()
|
||||
{
|
||||
if(!g_sltp_settings_valid)
|
||||
return;
|
||||
if(!g_sltp_settings.manager_enabled)
|
||||
return;
|
||||
|
||||
g_sltp_manager.ManagePositions();
|
||||
g_sltp_manager.HighVolatilityLimit();
|
||||
}
|
||||
|
||||
void OnChartEvent(const int id,
|
||||
const long &lparam,
|
||||
const double &dparam,
|
||||
const string &sparam)
|
||||
{
|
||||
if(!g_sltp_panel_created)
|
||||
return;
|
||||
|
||||
SLTPManagerPanelSettings candidate_settings = g_sltp_settings;
|
||||
if(g_sltp_panel.HandleChartEvent(id, lparam, dparam, sparam, candidate_settings))
|
||||
{
|
||||
if(!ApplySLTPSettings(candidate_settings, true))
|
||||
Print("HIT SLTP panel apply failed. Please review panel values.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Function implementations are kept in project headers so the EA entry points stay compact.
|
||||
#include <MyLib/Common/HITRuntimeController.mqh>
|
||||
#include <MyLib/Signals/HITEntrySignal.mqh>
|
||||
#include <MyLib/Common/HITExternalProcess.mqh>
|
||||
#include <MyLib/Signals/HITPythonSignalGateway.mqh>
|
||||
#include <MyLib/Trading/HITTradeManager.mqh>
|
||||
@@ -1,440 +0,0 @@
|
||||
//+------------------------------------------------------------------+
|
||||
//| HIT_EA.mq5 |
|
||||
//| Copyright 2026, nanpin-martin.com |
|
||||
//| https://www.nanpin-martin.com |
|
||||
//+------------------------------------------------------------------+
|
||||
#property copyright "Copyright 2026, nanpin-martin.com"
|
||||
#property link "https://nanpin-martin.com/"
|
||||
#property version "1.01"
|
||||
|
||||
#include <MyLib/Trading/SLTPManager.mqh>
|
||||
#include <MyLib/Panel/SLTPManagerPanel.mqh>
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| バッチファイル実行用の設定
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
// Windowsプロセス起動・終了確認用
|
||||
#define CREATE_NO_WINDOW 0x08000000
|
||||
#define PROCESS_QUERY_LIMITED_INFORMATION 0x00001000
|
||||
#define SYNCHRONIZE 0x00100000
|
||||
#define WAIT_OBJECT_0 0
|
||||
#define WAIT_TIMEOUT 258
|
||||
#define STILL_ACTIVE 259
|
||||
|
||||
struct STARTUPINFO_W
|
||||
{
|
||||
uint cb;
|
||||
string lpReserved;
|
||||
string lpDesktop;
|
||||
string lpTitle;
|
||||
uint dwX;
|
||||
uint dwY;
|
||||
uint dwXSize;
|
||||
uint dwYSize;
|
||||
uint dwXCountChars;
|
||||
uint dwYCountChars;
|
||||
uint dwFillAttribute;
|
||||
uint dwFlags;
|
||||
ushort wShowWindow;
|
||||
ushort cbReserved2;
|
||||
long lpReserved2;
|
||||
long hStdInput;
|
||||
long hStdOutput;
|
||||
long hStdError;
|
||||
};
|
||||
|
||||
struct PROCESS_INFORMATION
|
||||
{
|
||||
long hProcess;
|
||||
long hThread;
|
||||
uint dwProcessId;
|
||||
uint dwThreadId;
|
||||
};
|
||||
|
||||
#import "kernel32.dll"
|
||||
int CreateProcessW(string lpApplicationName, string lpCommandLine, long lpProcessAttributes, long lpThreadAttributes, int bInheritHandles, uint dwCreationFlags, long lpEnvironment, string lpCurrentDirectory, STARTUPINFO_W &lpStartupInfo, PROCESS_INFORMATION &lpProcessInformation);
|
||||
int WaitForSingleObject(long hHandle, uint dwMilliseconds);
|
||||
int GetExitCodeProcess(long hProcess, uint &lpExitCode);
|
||||
int CloseHandle(long hObject);
|
||||
long OpenProcess(uint dwDesiredAccess, int bInheritHandle, uint dwProcessId);
|
||||
#import
|
||||
|
||||
// バッチファイルのパス
|
||||
string get_trend_reply_bat = "C:\\ea_py\\bat\\get_trend_reply.bat"; // H4: trend
|
||||
string get_entry_reply_bat = "C:\\ea_py\\bat\\get_entry_reply.bat"; // H1: entry
|
||||
|
||||
// プロセス完了ファイルの設定
|
||||
string done_trend_file = "process_done_trend.txt";
|
||||
string done_entry_file = "process_done_entry.txt";
|
||||
|
||||
// Python出力ファイル
|
||||
string trend_state_file = "trend_state.txt";
|
||||
string target_prices_file = "target_prices.txt";
|
||||
|
||||
// Python実行中を判定するための管理ファイル
|
||||
string running_trend_file = "process_running_trend.txt";
|
||||
string running_entry_file = "process_running_entry.txt";
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| インプットの設定
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//--- 入力パラメータ
|
||||
input double lot_size = 0.01; // ロット数
|
||||
input double spread_limit = 60; // 許容スプレッド(point)
|
||||
input int magic_number = 10001; // マジックナンバー
|
||||
input int initial_order = 0; // 起動時の注文(0:なし, 1:あり)
|
||||
input bool use_m15_entry_filter = true; // M15確定足で発注タイミングを確認
|
||||
input double m15_entry_zone_atr_multiplier = 1.50; // M15平均レンジ何本分まで候補価格への接近を許可
|
||||
input bool use_m15_imbalance_confirmation = true; // T1/T3でM15初動確認を追加
|
||||
input int m15_imbalance_avg_body_period = 20; // M15平均実体計算期間
|
||||
input double m15_imbalance_sensitivity = 2.0; // M15初動検知感度
|
||||
input double m15_imbalance_min_avg_body_points = 1.0; // 平均実体の最小値(point)
|
||||
input bool use_m15_imbalance_debug_log = false; // M15初動確認ログ
|
||||
input bool input_sltp_manager_enabled = false; // UI連動SLTP管理を有効化
|
||||
input bool input_sltp_show_panel = true; // SLTP操作パネルを表示
|
||||
input bool input_sltp_use_breakeven = false; // 通常ブレークイーブンを有効化
|
||||
input double input_sltp_breakeven_trigger_pips = 30.0; // 通常BE開始pips
|
||||
input double input_sltp_breakeven_buffer_pips = 3.0; // 通常BE固定バッファpips
|
||||
input bool input_sltp_use_elapsed_breakeven = false; // 保有時間BEを有効化
|
||||
input double input_sltp_elapsed_breakeven_hours = 4.0; // 保有時間BE開始時間
|
||||
input double input_sltp_elapsed_breakeven_buffer_pips = 3.0; // 保有時間BE固定バッファpips
|
||||
input bool input_sltp_use_active_trailing = false; // アクティブトレーリングを有効化
|
||||
input double input_sltp_active_breakeven_pips = 30.0; // アクティブ開始pips
|
||||
input double input_sltp_active_stop_loss_offset_pips = 5.0; // 初期固定pips
|
||||
input double input_sltp_active_step_trigger_pips = 10.0; // ステップ更新間隔pips
|
||||
input double input_sltp_active_step_move_pips = 5.0; // 1ステップ固定追加pips
|
||||
input bool input_sltp_use_tp_progress_stop = false; // TP進捗SLを有効化
|
||||
input double input_sltp_tp_progress_trigger_percent = 70.0; // TP進捗SL開始率
|
||||
input double input_sltp_tp_progress_sl_lock_percent = 30.0; // TP距離固定率
|
||||
input bool input_sltp_use_high_volatility_limit = false; // 急変時SL引き締めを有効化
|
||||
ulong slippage = 10; // スリッページ
|
||||
|
||||
//--- 主要な定数・設定
|
||||
#define POSITION_LIMIT 48
|
||||
#define ENTRY_H1_LIMIT 1 // H1本数(=1時間)
|
||||
#define CLOSE_H1_LIMIT 12 // H1本数(=12時間)
|
||||
#define HISTORY_BARS 72
|
||||
#define OHLC_START_SHIFT 1 // 1: 確定足のみをPythonへ渡す
|
||||
#define M15_CONFIRM_BARS 30
|
||||
#define M15_MIN_ENTRY_ZONE_POINTS 10
|
||||
#define M15_MIN_BODY_RATIO 0.25
|
||||
#define M15_REJECTION_WICK_RATIO 0.35
|
||||
#define ENTRY_RETRY_SECONDS 60
|
||||
#define ENTRY_RETRY_LIMIT 10
|
||||
// ANALYZE_TIMEFRAME は削除(H4/H1 両方使うため定数ではなく直接指定)
|
||||
#define TARGET_SIZE 13
|
||||
#define DEFAULT_TARGET_PRICE 0.0
|
||||
#define PYTHON_TIMEOUT_SECONDS 600 // Python完了待ちの上限(秒)
|
||||
|
||||
#define MARKET_LOW_VOL_RANGE 0
|
||||
#define MARKET_HIGH_VOL_RANGE 1
|
||||
#define MARKET_LOW_VOL_UP 2
|
||||
#define MARKET_HIGH_VOL_UP 3
|
||||
#define MARKET_LOW_VOL_DOWN 4
|
||||
#define MARKET_HIGH_VOL_DOWN 5
|
||||
#define MARKET_TECHNICAL_ERROR_STOP 6
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| EAの状態をまとめる構造体
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
struct EAState
|
||||
{
|
||||
int trend_state; // H4 market_state(0..5、6は技術エラー停止)を格納する変数
|
||||
int res_chk; // GPTの回答が正しく取得できたか
|
||||
double en_price[5]; // エントリー基準価格
|
||||
double tp_price[5]; // 利益確定価格
|
||||
double sl_price[5]; // ロスカット基準価格
|
||||
bool load_trend_flg; // ★変更:トレンドを更新するタイミングか
|
||||
bool load_target_flg; // ★変更:ターゲット価格を更新するタイミングか
|
||||
int chk_cnt; // エントリー判定の試行回数
|
||||
datetime last_trend_update; // ★追加:前回トレンドを更新した時刻
|
||||
datetime last_target_update; // ★変更:前回ターゲット価格を更新した時刻
|
||||
datetime target_loaded_at; // H1候補価格をEAへ読み込んだサーバー時刻
|
||||
datetime last_chk;
|
||||
};
|
||||
|
||||
EAState g_ea; // EA全体の状態をここで管理
|
||||
|
||||
// initial_order 用の初回処理フラグ
|
||||
// H4トレンド処理とH1エントリー処理で別々に管理し、初回起動時の再実行ループを防ぐ。
|
||||
bool g_init_trend_pending = false;
|
||||
bool g_init_entry_pending = false;
|
||||
|
||||
// H4/H1のバー更新状態
|
||||
int g_pre_bars_H4 = 0;
|
||||
int g_pre_bars_H1 = 0;
|
||||
int g_pre_bars_M15 = 0;
|
||||
bool g_bars_H1_check = false;
|
||||
bool g_bars_M15_check = false;
|
||||
|
||||
// ティックごとの価格情報
|
||||
struct TickContext
|
||||
{
|
||||
double ask;
|
||||
double bid;
|
||||
double spread;
|
||||
double spread_points;
|
||||
int digits;
|
||||
};
|
||||
|
||||
// 外部Pythonプロセスの状態
|
||||
struct ExternalProcessState
|
||||
{
|
||||
long handle;
|
||||
uint process_id;
|
||||
bool active;
|
||||
bool exit_code_ready;
|
||||
uint exit_code;
|
||||
datetime started_at;
|
||||
};
|
||||
|
||||
ExternalProcessState g_trend_process;
|
||||
ExternalProcessState g_entry_process;
|
||||
|
||||
CSLTPManager g_sltp_manager;
|
||||
CSLTPManagerPanel g_sltp_panel;
|
||||
SLTPManagerPanelSettings g_sltp_settings;
|
||||
bool g_sltp_settings_valid = false;
|
||||
bool g_sltp_panel_created = false;
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 起動時の処理
|
||||
//+------------------------------------------------------------------+
|
||||
/**
|
||||
* @brief EA起動時の初期化処理を行います。
|
||||
*
|
||||
* Python連携用のdone/runningファイル状態を確認し、`initial_order` が有効な場合は
|
||||
* H4トレンド判定とH1エントリー価格生成をそれぞれ初回実行対象にします。
|
||||
* H4/H1の初回フラグを分けることで、起動直後にH4処理だけが繰り返される状態を防ぎます。
|
||||
*/
|
||||
int OnInit()
|
||||
// プロセス完了ファイルと実行中ファイルの状態を初期化
|
||||
{
|
||||
PrepareDoneFileOnInit(done_trend_file, running_trend_file, "trend");
|
||||
PrepareDoneFileOnInit(done_entry_file, running_entry_file, "entry");
|
||||
|
||||
// initial_order=1 の場合でも、H4/H1を別々に1回だけ初回実行する。
|
||||
g_init_trend_pending = (initial_order == 1);
|
||||
g_init_entry_pending = (initial_order == 1);
|
||||
|
||||
if(!InitializeSLTPManager())
|
||||
return INIT_FAILED;
|
||||
|
||||
return INIT_SUCCEEDED;
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| 終了時の処理
|
||||
//+------------------------------------------------------------------+
|
||||
void OnDeinit(const int reason)
|
||||
{
|
||||
ResetExternalProcessState(g_trend_process);
|
||||
ResetExternalProcessState(g_entry_process);
|
||||
|
||||
if(g_sltp_panel_created)
|
||||
g_sltp_panel.Destroy(reason);
|
||||
|
||||
// Clear chart status text left by Comment() when the EA is removed.
|
||||
Comment("");
|
||||
ChartRedraw(0);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| ティック毎の処理
|
||||
//+------------------------------------------------------------------+
|
||||
/**
|
||||
* @brief ティック受信ごとにEA全体の処理を制御します。
|
||||
*
|
||||
* 処理順序は、ティック情報取得、期限切れ注文/ポジション管理、H4トレンド更新、
|
||||
* H1エントリー価格更新、M15エントリータイミング更新、ステータス表示、新規注文判定の順です。
|
||||
* 時間制限処理はPython完了待ちやスプレッド判定より前に実行します。
|
||||
*/
|
||||
void OnTick()
|
||||
{
|
||||
TickContext ctx;
|
||||
if(!GetTickContext(ctx))
|
||||
return;
|
||||
|
||||
// 期限切れ注文・ポジションは、Python待ちやスプレッド制限に関係なく先に処理する。
|
||||
ManageExpiredTrades();
|
||||
|
||||
// Existing-position protection stays active even while Python results are pending.
|
||||
ManageSLTPPositions();
|
||||
|
||||
// 外部Pythonがdoneを返さない場合に、一定時間で待機状態を解除して再実行対象にする。
|
||||
RecoverTimedOutPythonProcesses();
|
||||
|
||||
// H4新バーまたは初回起動時に、トレンド判定用Pythonを起動する。
|
||||
ProcessTrendUpdate(g_ea);
|
||||
|
||||
// トレンド判定が完了していない場合、新規注文側の処理だけをスキップする。
|
||||
if(!IsTrendResultReady())
|
||||
return;
|
||||
|
||||
RefreshTrendState(g_ea);
|
||||
|
||||
// H1新バーまたは初回起動時に、エントリー価格生成用Pythonを起動する。
|
||||
ProcessEntryUpdate(g_ea);
|
||||
|
||||
// M15確定足ごとに、H1候補価格を発注してよいタイミングか再判定する。
|
||||
ProcessM15EntryTimingUpdate();
|
||||
|
||||
UpdateStatusComment(ctx);
|
||||
|
||||
// ここから下は新規注文に関する処理。
|
||||
if(!IsSpreadAllowed(ctx))
|
||||
return;
|
||||
|
||||
if(!IsEntryResultReady())
|
||||
return;
|
||||
|
||||
RefreshTargetPrices(g_ea);
|
||||
ProcessEntryDecisionIfNeeded(g_ea, ctx);
|
||||
}
|
||||
|
||||
//+------------------------------------------------------------------+
|
||||
//| SLTP manager panel and settings bridge
|
||||
//+------------------------------------------------------------------+
|
||||
string SLTPBoolText(const bool value)
|
||||
{
|
||||
return value ? "ON" : "OFF";
|
||||
}
|
||||
|
||||
void LoadSLTPInputSettings(SLTPManagerPanelSettings &settings)
|
||||
{
|
||||
settings.manager_enabled = input_sltp_manager_enabled;
|
||||
|
||||
settings.use_breakeven = input_sltp_use_breakeven;
|
||||
settings.breakeven_trigger_pips = input_sltp_breakeven_trigger_pips;
|
||||
settings.breakeven_buffer_pips = input_sltp_breakeven_buffer_pips;
|
||||
|
||||
settings.use_elapsed_breakeven = input_sltp_use_elapsed_breakeven;
|
||||
settings.elapsed_breakeven_hours = input_sltp_elapsed_breakeven_hours;
|
||||
settings.elapsed_breakeven_buffer_pips = input_sltp_elapsed_breakeven_buffer_pips;
|
||||
|
||||
settings.use_active_trailing = input_sltp_use_active_trailing;
|
||||
settings.active_breakeven_pips = input_sltp_active_breakeven_pips;
|
||||
settings.active_stop_loss_offset_pips = input_sltp_active_stop_loss_offset_pips;
|
||||
settings.active_step_trigger_pips = input_sltp_active_step_trigger_pips;
|
||||
settings.active_step_move_pips = input_sltp_active_step_move_pips;
|
||||
|
||||
settings.use_tp_progress_stop = input_sltp_use_tp_progress_stop;
|
||||
settings.tp_progress_trigger_percent = input_sltp_tp_progress_trigger_percent;
|
||||
settings.tp_progress_sl_lock_percent = input_sltp_tp_progress_sl_lock_percent;
|
||||
|
||||
settings.use_high_volatility_limit = input_sltp_use_high_volatility_limit;
|
||||
}
|
||||
|
||||
bool ApplySLTPSettings(const SLTPManagerPanelSettings &settings,
|
||||
const bool print_summary)
|
||||
{
|
||||
g_sltp_settings_valid = false;
|
||||
|
||||
g_sltp_manager.SetMagicNumber((ulong)magic_number);
|
||||
g_sltp_manager.SetSymbol(_Symbol);
|
||||
g_sltp_manager.SetDeviationInPoints(slippage);
|
||||
g_sltp_manager.SetBreakevenSettings(settings.use_breakeven,
|
||||
settings.breakeven_trigger_pips,
|
||||
settings.breakeven_buffer_pips);
|
||||
g_sltp_manager.SetElapsedBreakevenSettings(settings.use_elapsed_breakeven,
|
||||
settings.elapsed_breakeven_hours,
|
||||
settings.elapsed_breakeven_buffer_pips);
|
||||
g_sltp_manager.SetActiveTrailingSettings(settings.use_active_trailing,
|
||||
settings.active_breakeven_pips,
|
||||
settings.active_stop_loss_offset_pips,
|
||||
settings.active_step_trigger_pips,
|
||||
settings.active_step_move_pips);
|
||||
g_sltp_manager.SetTpProgressStopSettings(settings.use_tp_progress_stop,
|
||||
settings.tp_progress_trigger_percent,
|
||||
settings.tp_progress_sl_lock_percent);
|
||||
g_sltp_manager.SetHighVolatilityLimitSettings(settings.use_high_volatility_limit);
|
||||
|
||||
if(!g_sltp_manager.ValidateSettings())
|
||||
{
|
||||
Print("HIT SLTP settings rejected. Manager is disabled until valid settings are applied.");
|
||||
return false;
|
||||
}
|
||||
|
||||
g_sltp_settings = settings;
|
||||
g_sltp_settings_valid = true;
|
||||
|
||||
if(print_summary)
|
||||
{
|
||||
Print("HIT SLTP settings: Manager=", SLTPBoolText(settings.manager_enabled),
|
||||
" BE=", SLTPBoolText(settings.use_breakeven),
|
||||
" ElapsedBE=", SLTPBoolText(settings.use_elapsed_breakeven),
|
||||
" ActiveTrail=", SLTPBoolText(settings.use_active_trailing),
|
||||
" TPProgress=", SLTPBoolText(settings.use_tp_progress_stop),
|
||||
" HighVol=", SLTPBoolText(settings.use_high_volatility_limit));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool InitializeSLTPManager()
|
||||
{
|
||||
SLTPManagerPanelSettings initial_settings;
|
||||
LoadSLTPInputSettings(initial_settings);
|
||||
|
||||
if(!ApplySLTPSettings(initial_settings, true))
|
||||
return false;
|
||||
|
||||
g_sltp_panel.Init(g_sltp_settings);
|
||||
if(input_sltp_show_panel)
|
||||
{
|
||||
if(!g_sltp_panel.CreatePanel())
|
||||
{
|
||||
Print("HIT SLTP panel is unavailable. EA continues with input-based SLTP settings.");
|
||||
return true;
|
||||
}
|
||||
|
||||
g_sltp_panel.SetInitialValues();
|
||||
g_sltp_panel_created = true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ManageSLTPPositions()
|
||||
{
|
||||
if(!g_sltp_settings_valid)
|
||||
return;
|
||||
if(!g_sltp_settings.manager_enabled)
|
||||
return;
|
||||
|
||||
g_sltp_manager.ManagePositions();
|
||||
g_sltp_manager.HighVolatilityLimit();
|
||||
}
|
||||
|
||||
void OnChartEvent(const int id,
|
||||
const long &lparam,
|
||||
const double &dparam,
|
||||
const string &sparam)
|
||||
{
|
||||
if(!g_sltp_panel_created)
|
||||
return;
|
||||
|
||||
SLTPManagerPanelSettings candidate_settings = g_sltp_settings;
|
||||
if(g_sltp_panel.HandleChartEvent(id, lparam, dparam, sparam, candidate_settings))
|
||||
{
|
||||
if(!ApplySLTPSettings(candidate_settings, true))
|
||||
Print("HIT SLTP panel apply failed. Please review panel values.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Function implementations are kept in project headers so the EA entry points stay compact.
|
||||
#include <MyLib/Common/HITRuntimeController.mqh>
|
||||
#include <MyLib/Signals/HITEntrySignal.mqh>
|
||||
#include <MyLib/Common/HITExternalProcess.mqh>
|
||||
#include <MyLib/Signals/HITPythonSignalGateway.mqh>
|
||||
#include <MyLib/Trading/HITTradeManager.mqh>
|
||||
Reference in New Issue
Block a user