-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUpdateHass.mq4
More file actions
166 lines (144 loc) · 7.78 KB
/
Copy pathUpdateHass.mq4
File metadata and controls
166 lines (144 loc) · 7.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
//+------------------------------------------------------------------+
//| UpdateHass.mq4 |
//| James Pattinson |
//| |
//+------------------------------------------------------------------+
#property copyright "James Pattinson"
#property link "https://github.com/SupraJames/MT4-HA"
#property version "1.00"
#property strict
input string HassUrl = "https://hass.domain.org/";
input string HassToken = "";
input string webHookId = "";
input string HassSensorPrefix = "forexacct";
input string HassUpdateInterval = 120;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create timer
EventSetTimer(HassUpdateInterval);
Print("Timer registered with interval " + HassUpdateInterval + " seconds");
UpdateHass();
webhookHeartbeat();
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- destroy timer
EventKillTimer();
}
double getClosedPnlOfDay()
{
// Note that this is the timestamp of the LAST TRADE/TICK and NOT the actual Time!
const datetime curTime = TimeCurrent();
const datetime timeStart = StrToTime(IntegerToString(Year()) + "." + IntegerToString(Month()) + "." + IntegerToString(Day()) + " 00:00");
double result=0.;
for(int i=OrdersHistoryTotal()-1;i>=0;i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))continue;
// Filter out any trades without 'Standard' as the comment
if(!StringCompare(StringSubstr(OrderComment(),0,7),"Deposit" )) continue;
if(!StringCompare(StringSubstr(OrderComment(),0,8),"Withdraw" )) continue;
if(!StringCompare(StringSubstr(OrderComment(),0,8),"Transfer" )) continue;
//Print("DEBUG: Comment of order #", OrderTicket(), " is ", OrderComment());
if(OrderCloseTime()<timeStart || OrderCloseTime()>=curTime) continue;
double ordProfit = OrderProfit() + OrderCommission() + OrderSwap();
//Print("DEBUG: Order " + OrderTicket() + " value " + ordProfit);
result+=ordProfit;
}
//Print("DEBUG: total is " + result);
return result;
}
//+------------------------------------------------------------------+
//| Timer function |
//+------------------------------------------------------------------+
void UpdateHass()
{
UpdateSensor(HassSensorPrefix + "_ping", StringFormat( "{\"state\": %.1f, \"attributes\": {\"unit_of_measurement\": \"ms\" }}", TerminalInfoInteger(TERMINAL_PING_LAST)/1000));
UpdateSensor(HassSensorPrefix + "_openpos", StringFormat( "{\"state\": %.2f, \"attributes\": {\"unit_of_measurement\": \"EUR\" }}", -AccountProfit()));
UpdateSensor(HassSensorPrefix + "_profit", StringFormat( "{\"state\": %.2f, \"attributes\": {\"unit_of_measurement\": \"EUR\" }}", getClosedPnlOfDay()));
UpdateSensor(HassSensorPrefix + "_balance", StringFormat( "{\"state\": %.2f, \"attributes\": {\"unit_of_measurement\": \"EUR\" }}", AccountBalance()));
UpdateSensor(HassSensorPrefix + "_ddpct", StringFormat( "{\"state\": %.2f, \"attributes\": {\"unit_of_measurement\": \"%\" }}", (-AccountProfit()/AccountBalance())*100));
}
//+------------------------------------------------------------------+
void UpdateSensor(string HassSensorEntity, string JSON_string)
{
string ReqSERVER_URL = HassUrl + "api/states/sensor." + HassSensorEntity,
ReqCOOKIE = NULL,
ReqHEADERs = "Content-Type: application/json\r\nauthorization: Bearer " + HassToken + "\r\n";
int ReqTIMEOUT = 5000;
char POSTed_DATA[],
result_RECVed_DATA_FromSERVER[];
int result_RetCODE;
string result_DecodedFromSERVER,
result_RECVed_HDRs_FromSERVER;
StringToCharArray( JSON_string, POSTed_DATA, 0, StringLen( JSON_string ) );
ResetLastError();
result_RetCODE = WebRequest( "POST",
ReqSERVER_URL,
ReqHEADERs,
ReqTIMEOUT,
POSTed_DATA,
result_RECVed_DATA_FromSERVER,
result_RECVed_HDRs_FromSERVER
);
if ( result_RetCODE == -1 ) Print( "Error in WebRequest. Error code =", GetLastError() ); // returns error 4060 – "Function is not allowed for call" unless permitted -- ref. Picture in >>> https://stackoverflow.com/questions/39954177/how-to-send-a-post-with-a-json-in-a-webrequest-call-using-mql4
else {
for ( int i = 0; i < ArraySize( result_RECVed_DATA_FromSERVER ); i++ ) {
if ( ( result_RECVed_DATA_FromSERVER[i] == 10 ) // == '\n' // <LF>
|| ( result_RECVed_DATA_FromSERVER[i] == 13 ) // == '\r' // <CR>
)
continue;
else result_DecodedFromSERVER += CharToStr( result_RECVed_DATA_FromSERVER[i] );
}
//Print( "DATA:: ", result_DecodedFromSERVER );
//Print( "HDRs:: ", result_RECVed_HDRs_FromSERVER );
}
}
void webhookHeartbeat()
{
string ReqSERVER_URL = HassUrl + "api/webhook/" + webHookId,
ReqCOOKIE = NULL,
ReqHEADERs = "Content-Type: application/json\r\n";
int ReqTIMEOUT = 5000;
char POSTed_DATA[],
result_RECVed_DATA_FromSERVER[];
int result_RetCODE;
string result_DecodedFromSERVER,
result_RECVed_HDRs_FromSERVER;
string JSON_string = "{dummydata: 0}";
StringToCharArray( JSON_string, POSTed_DATA, 0, StringLen(JSON_string) );
ResetLastError();
result_RetCODE = WebRequest( "POST",
ReqSERVER_URL,
ReqHEADERs,
ReqTIMEOUT,
POSTed_DATA,
result_RECVed_DATA_FromSERVER,
result_RECVed_HDRs_FromSERVER
);
if ( result_RetCODE == -1 ) Print( "Error in WebRequest. Error code =", GetLastError() ); // returns error 4060 – "Function is not allowed for call" unless permitted -- ref. Picture in >>> https://stackoverflow.com/questions/39954177/how-to-send-a-post-with-a-json-in-a-webrequest-call-using-mql4
else {
for ( int i = 0; i < ArraySize( result_RECVed_DATA_FromSERVER ); i++ ) {
if ( ( result_RECVed_DATA_FromSERVER[i] == 10 ) // == '\n' // <LF>
|| ( result_RECVed_DATA_FromSERVER[i] == 13 ) // == '\r' // <CR>
)
continue;
else result_DecodedFromSERVER += CharToStr( result_RECVed_DATA_FromSERVER[i] );
}
//Print(ReqSERVER_URL);
//Print( "DATA:: ", result_DecodedFromSERVER );
//Print( "HDRs:: ", result_RECVed_HDRs_FromSERVER );
}
}
void OnTimer()
{
UpdateHass();
//webhookHeartbeat();
}