Issue #89: Changed function OrderCheck to use json request/response

This commit is contained in:
vdemydiuk
2018-02-19 17:02:19 +02:00
parent d6640300f5
commit f1c1df1e00
12 changed files with 141 additions and 131 deletions
+5
View File
@@ -31,5 +31,10 @@ namespace MtApi5
Margin_level = margin_level; Margin_level = margin_level;
Comment = comment; Comment = comment;
} }
public override string ToString()
{
return $"Retcode={Retcode}; Comment={Comment}; Balance={Balance}; Equity={Equity}; Profit={Profit}; Margin={Margin}; Margin_free={Margin_free}; Margin_level={Margin_level}";
}
} }
} }
+2 -2
View File
@@ -9,7 +9,7 @@ namespace MtApi5
//OrderSend = 1, //OrderSend = 1,
OrderCalcMargin = 2, OrderCalcMargin = 2,
OrderCalcProfit = 3, OrderCalcProfit = 3,
OrderCheck = 4, //OrderCheck = 4,
//OrderSendAsync = 5, //OrderSendAsync = 5,
PositionsTotal = 6, PositionsTotal = 6,
PositionGetSymbol = 7, PositionGetSymbol = 7,
@@ -101,7 +101,7 @@ namespace MtApi5
//CTrade //CTrade
PositionClose = 64, PositionClose = 64,
PositionOpen = 65, PositionOpen = 65,
PositionOpenWithResult = 1065, //PositionOpenWithResult = 1065,
//Backtesting //Backtesting
BacktestingReady = 66, BacktestingReady = 66,
+2
View File
@@ -68,6 +68,8 @@
<Compile Include="Mt5Quote.cs" /> <Compile Include="Mt5Quote.cs" />
<Compile Include="Requests\CopyTicksRequest.cs" /> <Compile Include="Requests\CopyTicksRequest.cs" />
<Compile Include="Requests\ICustomRequest.cs" /> <Compile Include="Requests\ICustomRequest.cs" />
<Compile Include="Requests\OrderCheckRequest.cs" />
<Compile Include="Requests\OrderCheckResult.cs" />
<Compile Include="Requests\OrderSendRequest.cs" /> <Compile Include="Requests\OrderSendRequest.cs" />
<Compile Include="Requests\PositionOpenRequest.cs" /> <Compile Include="Requests\PositionOpenRequest.cs" />
<Compile Include="Requests\RequestBase.cs" /> <Compile Include="Requests\RequestBase.cs" />
+9 -9
View File
@@ -187,17 +187,22 @@ namespace MtApi5
/// </returns> /// </returns>
public bool OrderCheck(MqlTradeRequest request, out MqlTradeCheckResult result) public bool OrderCheck(MqlTradeRequest request, out MqlTradeCheckResult result)
{ {
Log.Debug($"OrderCheck: request = {request}");
if (request == null) if (request == null)
{ {
Log.Warn("OrderCheck: request is not defined!");
result = null; result = null;
return false; return false;
} }
var commandParameters = request.ToArrayList(); var response = SendRequest<OrderCheckResult>(new OrderCheckRequest
{
TradeRequest = request
});
var strResult = SendCommand<string>(Mt5CommandType.OrderCheck, commandParameters); result = response?.TradeCheckResult;
return response != null && response.RetVal;
return strResult.ParseResult(ParamSeparator, out result);
} }
///<summary> ///<summary>
@@ -559,11 +564,6 @@ namespace MtApi5
result = response?.TradeResult; result = response?.TradeResult;
return response != null && response.RetVal; return response != null && response.RetVal;
//var commandParameters = new ArrayList { symbol, (int)orderType, volume, price, sl, tp, comment };
//var strResult = SendCommand<string>(Mt5CommandType.PositionOpenWithResult, commandParameters);
//return strResult.ParseResult(ParamSeparator, out result);
} }
#endregion #endregion
-43
View File
@@ -14,49 +14,6 @@ namespace MtApi5
return quote != null ? new Mt5Quote(quote.Instrument, quote.Bid, quote.Ask) : null; return quote != null ? new Mt5Quote(quote.Instrument, quote.Bid, quote.Ask) : null;
} }
//public static bool ParseResult(this string inputString, char separator, out MqlTradeResult result)
//{
// Log.Debug($"ParseResult: inputString = {inputString}, separator = {separator}");
// var retVal = false;
// result = null;
// if (string.IsNullOrEmpty(inputString) == false)
// {
// var values = inputString.Split(separator);
// if (values.Length == 10)
// {
// try
// {
// retVal = int.Parse(values[0]) != 0;
// var retcode = uint.Parse(values[1]);
// var deal = ulong.Parse(values[2]);
// var order = ulong.Parse(values[3]);
// var volume = double.Parse(values[4]);
// var price = double.Parse(values[5]);
// var bid = double.Parse(values[6]);
// var ask = double.Parse(values[7]);
// var comment = values[8];
// var requestId = uint.Parse(values[9]);
// result = new MqlTradeResult(retcode, deal, order, volume, price, bid, ask, comment, requestId);
// }
// catch (Exception ex)
// {
// Log.Error($"ParseResult: {ex.Message}");
// retVal = false;
// }
// }
// }
// else
// {
// Log.Warn("ParseResult: input srting is null or empty!");
// }
// return retVal;
//}
public static bool ParseResult(this string inputString, char separator, out MqlTradeCheckResult result) public static bool ParseResult(this string inputString, char separator, out MqlTradeCheckResult result)
{ {
Log.Debug($"ParseResult: inputString = {inputString}, separator = {separator}"); Log.Debug($"ParseResult: inputString = {inputString}, separator = {separator}");
+10
View File
@@ -0,0 +1,10 @@
namespace MtApi5.Requests
{
internal class OrderCheckRequest: RequestBase
{
public override RequestType RequestType => RequestType.OrderCheck;
public MqlTradeRequest TradeRequest { get; set; }
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace MtApi5.Requests
{
public class OrderCheckResult
{
public bool RetVal { get; set; }
public MqlTradeCheckResult TradeCheckResult { get; set; }
}
}
+2 -1
View File
@@ -8,6 +8,7 @@ namespace MtApi5.Requests
CopyTicks = 1, CopyTicks = 1,
iCustom = 2, iCustom = 2,
OrderSend = 3, OrderSend = 3,
PositionOpen = 4 PositionOpen = 4,
OrderCheck = 5
} }
} }
+34 -53
View File
@@ -4,7 +4,7 @@
xmlns:mtapi5="clr-namespace:MtApi5;assembly=MtApi5" xmlns:mtapi5="clr-namespace:MtApi5;assembly=MtApi5"
xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:mtApi5TestClient="clr-namespace:MtApi5TestClient" xmlns:mtApi5TestClient="clr-namespace:MtApi5TestClient"
Title="MainWindow" Height="700" Width="650" Title="MainWindow" Height="700" Width="700"
Closing="Window_Closing"> Closing="Window_Closing">
<Window.Resources> <Window.Resources>
<DataTemplate x:Key="ConnectionTextBlockTemplate" DataType="{x:Type mtapi5:Mt5ConnectionState}"> <DataTemplate x:Key="ConnectionTextBlockTemplate" DataType="{x:Type mtapi5:Mt5ConnectionState}">
@@ -100,58 +100,33 @@
<ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<Expander ExpandDirection="Right" IsExpanded="True" <Grid Margin="10">
Grid.Row="0" Grid.Column="0" Margin="5"> <Grid.RowDefinitions>
<Expander.Header> <RowDefinition Height="Auto"/>
<TextBlock Text="Connection" RenderTransformOrigin="0.5,0.5" Margin="0,0,0,0" Width="Auto"> <RowDefinition Height="Auto"/>
<TextBlock.LayoutTransform> <RowDefinition Height="Auto"/>
<TransformGroup> </Grid.RowDefinitions>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="-90"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</TextBlock.LayoutTransform>
<TextBlock.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="0"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</TextBlock.RenderTransform>
</TextBlock>
</Expander.Header>
<Expander.Content>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="150"/> <ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Host"/> <TextBlock Grid.Row="0" Grid.Column="0" Text="Host"/>
<TextBox Grid.Row="0" Grid.Column="1" <TextBox Grid.Row="0" Grid.Column="1"
Margin="5,0,0,0" Margin="5,0,0,0"
Text="{Binding Host, UpdateSourceTrigger=PropertyChanged}"/> Text="{Binding Host, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Port"/> <TextBlock Grid.Row="1" Grid.Column="0" Text="Port"/>
<TextBox Grid.Row="1" Grid.Column="1" <TextBox Grid.Row="1" Grid.Column="1"
Margin="5,0,0,0" Margin="5,0,0,0"
Text="{Binding Port, UpdateSourceTrigger=PropertyChanged}"/> Text="{Binding Port, UpdateSourceTrigger=PropertyChanged}"/>
<StackPanel Grid.Row="2" Grid.ColumnSpan="2" Margin="5" Orientation="Horizontal"> <StackPanel Grid.Row="2" Grid.ColumnSpan="2" Margin="5" Orientation="Horizontal">
<Button Content="Connect" Width="70" Command="{Binding ConnectCommand}" /> <Button Content="Connect" Width="70" Command="{Binding ConnectCommand}" />
<Button Margin="5,0,0,0" Width="70" Content="Disconnect" Command="{Binding DisconnectCommand}" /> <Button Margin="5,0,0,0" Width="70" Content="Disconnect" Command="{Binding DisconnectCommand}" />
</StackPanel> </StackPanel>
</Grid> </Grid>
</Expander.Content>
</Expander>
<ListView Grid.Row="0" Grid.Column="1" <ListView Grid.Row="0" Grid.Column="1"
ItemsSource="{Binding Quotes}" ItemsSource="{Binding Quotes}"
@@ -255,12 +230,18 @@
</Expander> </Expander>
<StackPanel Grid.Row="1" Orientation="Vertical"> <StackPanel Grid.Row="1" Orientation="Vertical">
<Button Content="OrderSend" Command="{Binding OrderSendCommand}" Width="100" Height="25" HorizontalAlignment="Left" Margin="4"/> <StackPanel Orientation="Horizontal">
<Button Content="HistoryDealGetDouble" Command="{Binding HistoryDealGetDoubleCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/> <Button Content="OrderSend" Command="{Binding OrderSendCommand}" Width="100" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealGetInteger" Command="{Binding HistoryDealGetIntegerCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/> <Button Content="OrderCheck" Command="{Binding OrderCheckCommand}" Width="100" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealGetString" Command="{Binding HistoryDealGetStringCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/> </StackPanel>
<Button Content="HistoryOrderGetInteger" Command="{Binding HistoryOrderGetIntegerCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealMethods" Command="{Binding HistoryDealMethodsCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/> <WrapPanel>
<Button Content="HistoryDealGetDouble" Command="{Binding HistoryDealGetDoubleCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealGetInteger" Command="{Binding HistoryDealGetIntegerCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealGetString" Command="{Binding HistoryDealGetStringCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryOrderGetInteger" Command="{Binding HistoryOrderGetIntegerCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealMethods" Command="{Binding HistoryDealMethodsCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
</WrapPanel>
</StackPanel> </StackPanel>
</Grid> </Grid>
@@ -410,8 +391,8 @@
</TabItem> </TabItem>
</TabControl> </TabControl>
<Expander Grid.Row="2" Header="History" IsExpanded="True"> <Expander Grid.Row="2" Header="Console" IsExpanded="True">
<ListBox mtApi5TestClient:ListBoxBehavior.ScrollOnNewItem="true" Height="200" ItemsSource="{Binding History}"/> <ListBox mtApi5TestClient:ListBoxBehavior.ScrollOnNewItem="true" Height="180" ItemsSource="{Binding History}"/>
</Expander> </Expander>
<StatusBar Grid.Row="3"> <StatusBar Grid.Row="3">
+27 -22
View File
@@ -1,4 +1,5 @@
using System; // ReSharper disable InconsistentNaming
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Windows; using System.Windows;
@@ -16,6 +17,8 @@ namespace MtApi5TestClient
public DelegateCommand DisconnectCommand { get; private set; } public DelegateCommand DisconnectCommand { get; private set; }
public DelegateCommand OrderSendCommand { get; private set; } public DelegateCommand OrderSendCommand { get; private set; }
public DelegateCommand OrderCheckCommand { get; private set; }
public DelegateCommand HistoryOrderGetIntegerCommand { get; private set; } public DelegateCommand HistoryOrderGetIntegerCommand { get; private set; }
public DelegateCommand HistoryDealGetDoubleCommand { get; private set; } public DelegateCommand HistoryDealGetDoubleCommand { get; private set; }
public DelegateCommand HistoryDealGetIntegerCommand { get; private set; } public DelegateCommand HistoryDealGetIntegerCommand { get; private set; }
@@ -200,6 +203,8 @@ namespace MtApi5TestClient
DisconnectCommand = new DelegateCommand(ExecuteDisconnect, CanExecuteDisconnect); DisconnectCommand = new DelegateCommand(ExecuteDisconnect, CanExecuteDisconnect);
OrderSendCommand = new DelegateCommand(ExecuteOrderSend); OrderSendCommand = new DelegateCommand(ExecuteOrderSend);
OrderCheckCommand = new DelegateCommand(ExecuteOrderCheck);
HistoryOrderGetIntegerCommand = new DelegateCommand(ExecuteHistoryOrderGetInteger); HistoryOrderGetIntegerCommand = new DelegateCommand(ExecuteHistoryOrderGetInteger);
HistoryDealGetDoubleCommand = new DelegateCommand(ExecuteHistoryDealGetDouble); HistoryDealGetDoubleCommand = new DelegateCommand(ExecuteHistoryDealGetDouble);
HistoryDealGetIntegerCommand = new DelegateCommand(ExecuteHistoryDealGetInteger); HistoryDealGetIntegerCommand = new DelegateCommand(ExecuteHistoryDealGetInteger);
@@ -280,7 +285,22 @@ namespace MtApi5TestClient
return ok; return ok;
}); });
var message = retVal ? $"OrderSend excute successed. {MqlTradeResultToString(result)}" : $"OrderSend execute failed. {MqlTradeResultToString(result)}"; var message = retVal ? $"OrderSend: success. {result}" : $"OrderSend: fail. {result}";
AddLog(message);
}
private async void ExecuteOrderCheck(object obj)
{
var request = TradeRequest.GetMqlTradeRequest();
MqlTradeCheckResult result = null;
var retVal = await Execute(() =>
{
var ok = _mtApiClient.OrderCheck(request, out result);
return ok;
});
var message = retVal ? $"OrderCheck: success. {result}" : $"OrderCheck: fail. {result}";
AddLog(message); AddLog(message);
} }
@@ -328,15 +348,14 @@ namespace MtApi5TestClient
{ {
try try
{ {
var posId = await Execute(() => _mtApiClient.PositionGetInteger(ENUM_POSITION_PROPERTY_INTEGER.POSITION_IDENTIFIER)); // posId = 7247951 var posId = await Execute(() => _mtApiClient.PositionGetInteger(ENUM_POSITION_PROPERTY_INTEGER.POSITION_IDENTIFIER));
var history = await Execute(() => _mtApiClient.HistorySelectByPosition(posId)); // history = true var history = await Execute(() => _mtApiClient.HistorySelectByPosition(posId));
var historyDealsTotal = await Execute(() => _mtApiClient.HistoryDealsTotal()); // historyDealsCount = 4 var historyDealsTotal = await Execute(() => _mtApiClient.HistoryDealsTotal());
var histDealTicket = await Execute(() => _mtApiClient.HistoryDealGetTicket(0)); // histDealTicket = 6632442 var histDealTicket = await Execute(() => _mtApiClient.HistoryDealGetTicket(0));
var histDealPrice = await Execute(() => _mtApiClient.HistoryDealGetDouble(histDealTicket, ENUM_DEAL_PROPERTY_DOUBLE.DEAL_PRICE)); // Exception var histDealPrice = await Execute(() => _mtApiClient.HistoryDealGetDouble(histDealTicket, ENUM_DEAL_PROPERTY_DOUBLE.DEAL_PRICE));
} }
catch (Exception ex) catch (Exception ex)
{ {
// ex.Messsage = "Service connection failed! Ошибка сериализации параметра http://tempuri.org/:command. Сообщение InnerException было \"Тип \"MtApi5.ENUM_DEAL_PROPERTY_DOUBLE\" с именем контракта данных \"ENUM_DEAL_PROPERTY_DOUBLE:http://schemas.datacontract.org/2004/07/MtApi5\" не ожидается. Попробуйте использовать DataContractResolver, если вы используете DataContractSerializer, или добавьте любые статически неизвестные типы в список известных типов - например, используя атрибут KnownTypeAttribute или путем их добавления в список известных типов, передаваемый в сериализатор.\". Подробнее см. InnerException."
AddLog(ex.Message); AddLog(ex.Message);
return; return;
} }
@@ -969,20 +988,6 @@ namespace MtApi5TestClient
Quotes.Clear(); Quotes.Clear();
} }
private static string MqlTradeResultToString(MqlTradeResult result)
{
return result != null ?
"Retcode = " + result.Retcode + ";"
+ " Comment = " + result.Comment + ";"
+ " Order = " + result.Order + ";"
+ " Volume = " + result.Volume + ";"
+ " Price = " + result.Price + ";"
+ " Deal = " + result.Deal + ";"
+ " Request_id = " + result.Request_id + ";"
+ " Bid = " + result.Bid + ";"
+ " Ask = " + result.Ask + ";" : string.Empty;
}
private void OnSelectedQuoteChanged() private void OnSelectedQuoteChanged()
{ {
if (SelectedQuote == null) return; if (SelectedQuote == null) return;
BIN
View File
Binary file not shown.
+42 -1
View File
@@ -39,7 +39,7 @@
bool getBooleanValue(int expertHandle, int paramIndex, bool& res, string& err); bool getBooleanValue(int expertHandle, int paramIndex, bool& res, string& err);
#import #import
#define __DEBUG_LOG__ //#define __DEBUG_LOG__
input int Port = 8228; input int Port = 8228;
@@ -5588,6 +5588,9 @@ string OnRequest(string json)
case 4: //PositionOpen case 4: //PositionOpen
response = ExecuteRequest_PositionOpen(jo); response = ExecuteRequest_PositionOpen(jo);
break; break;
case 5: //OrderCheck
response = ExecuteRequest_OrderCheck(jo);
break;
default: default:
PrintFormat("%s [WARNING]: Unknown request type %d", __FUNCTION__, requestType); PrintFormat("%s [WARNING]: Unknown request type %d", __FUNCTION__, requestType);
response = CreateErrorResponse(-1, "Unknown request type"); response = CreateErrorResponse(-1, "Unknown request type");
@@ -5950,3 +5953,41 @@ string ExecuteRequest_PositionOpen(JSONObject *jo)
return CreateSuccessResponse("Value", result_value_jo); return CreateSuccessResponse("Value", result_value_jo);
} }
JSONObject* MqlTradeCheckResultToJson(MqlTradeCheckResult& result)
{
JSONObject* jo = new JSONObject();
jo.put("Retcode", new JSONNumber(result.retcode));
jo.put("Balance", new JSONNumber(result.balance));
jo.put("Equity", new JSONNumber(result.equity));
jo.put("Profit", new JSONNumber(result.profit));
jo.put("Margin", new JSONNumber(result.margin));
jo.put("Margin_free", new JSONNumber(result.margin_free));
jo.put("Margin_level", new JSONNumber(result.margin_level));
jo.put("Comment", new JSONString(result.comment));
return jo;
}
string ExecuteRequest_OrderCheck(JSONObject *jo)
{
CHECK_JSON_VALUE(jo, "TradeRequest", CreateErrorResponse(-1, "Undefinded mandatory parameter TradeRequest"));
JSONObject* trade_request_jo = jo.getObject("TradeRequest");
MqlTradeRequest trade_request = {0};
JsonToMqlTradeRequest(trade_request_jo, trade_request);
MqlTradeCheckResult trade_check_result = {0};
bool ok = OrderCheck(trade_request, trade_check_result);
#ifdef __DEBUG_LOG__
PrintFormat("%s: return value = %s", __FUNCTION__, ok ? "true" : "false");
#endif
JSONObject* result_value_jo = new JSONObject();
result_value_jo.put("RetVal", new JSONBool(ok));
result_value_jo.put("TradeCheckResult", MqlTradeCheckResultToJson(trade_check_result));
return CreateSuccessResponse("Value", result_value_jo);
}