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;
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,
OrderCalcMargin = 2,
OrderCalcProfit = 3,
OrderCheck = 4,
//OrderCheck = 4,
//OrderSendAsync = 5,
PositionsTotal = 6,
PositionGetSymbol = 7,
@@ -101,7 +101,7 @@ namespace MtApi5
//CTrade
PositionClose = 64,
PositionOpen = 65,
PositionOpenWithResult = 1065,
//PositionOpenWithResult = 1065,
//Backtesting
BacktestingReady = 66,
+2
View File
@@ -68,6 +68,8 @@
<Compile Include="Mt5Quote.cs" />
<Compile Include="Requests\CopyTicksRequest.cs" />
<Compile Include="Requests\ICustomRequest.cs" />
<Compile Include="Requests\OrderCheckRequest.cs" />
<Compile Include="Requests\OrderCheckResult.cs" />
<Compile Include="Requests\OrderSendRequest.cs" />
<Compile Include="Requests\PositionOpenRequest.cs" />
<Compile Include="Requests\RequestBase.cs" />
+9 -9
View File
@@ -187,17 +187,22 @@ namespace MtApi5
/// </returns>
public bool OrderCheck(MqlTradeRequest request, out MqlTradeCheckResult result)
{
Log.Debug($"OrderCheck: request = {request}");
if (request == null)
{
Log.Warn("OrderCheck: request is not defined!");
result = null;
return false;
}
var commandParameters = request.ToArrayList();
var response = SendRequest<OrderCheckResult>(new OrderCheckRequest
{
TradeRequest = request
});
var strResult = SendCommand<string>(Mt5CommandType.OrderCheck, commandParameters);
return strResult.ParseResult(ParamSeparator, out result);
result = response?.TradeCheckResult;
return response != null && response.RetVal;
}
///<summary>
@@ -559,11 +564,6 @@ namespace MtApi5
result = response?.TradeResult;
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
-43
View File
@@ -14,49 +14,6 @@ namespace MtApi5
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)
{
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,
iCustom = 2,
OrderSend = 3,
PositionOpen = 4
PositionOpen = 4,
OrderCheck = 5
}
}
+34 -53
View File
@@ -4,7 +4,7 @@
xmlns:mtapi5="clr-namespace:MtApi5;assembly=MtApi5"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:mtApi5TestClient="clr-namespace:MtApi5TestClient"
Title="MainWindow" Height="700" Width="650"
Title="MainWindow" Height="700" Width="700"
Closing="Window_Closing">
<Window.Resources>
<DataTemplate x:Key="ConnectionTextBlockTemplate" DataType="{x:Type mtapi5:Mt5ConnectionState}">
@@ -100,58 +100,33 @@
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Expander ExpandDirection="Right" IsExpanded="True"
Grid.Row="0" Grid.Column="0" Margin="5">
<Expander.Header>
<TextBlock Text="Connection" RenderTransformOrigin="0.5,0.5" Margin="0,0,0,0" Width="Auto">
<TextBlock.LayoutTransform>
<TransformGroup>
<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 Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Host"/>
<TextBox Grid.Row="0" Grid.Column="1"
<TextBlock Grid.Row="0" Grid.Column="0" Text="Host"/>
<TextBox Grid.Row="0" Grid.Column="1"
Margin="5,0,0,0"
Text="{Binding Host, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Port"/>
<TextBox Grid.Row="1" Grid.Column="1"
<TextBlock Grid.Row="1" Grid.Column="0" Text="Port"/>
<TextBox Grid.Row="1" Grid.Column="1"
Margin="5,0,0,0"
Text="{Binding Port, UpdateSourceTrigger=PropertyChanged}"/>
<StackPanel Grid.Row="2" Grid.ColumnSpan="2" Margin="5" Orientation="Horizontal">
<Button Content="Connect" Width="70" Command="{Binding ConnectCommand}" />
<Button Margin="5,0,0,0" Width="70" Content="Disconnect" Command="{Binding DisconnectCommand}" />
</StackPanel>
</Grid>
</Expander.Content>
</Expander>
<StackPanel Grid.Row="2" Grid.ColumnSpan="2" Margin="5" Orientation="Horizontal">
<Button Content="Connect" Width="70" Command="{Binding ConnectCommand}" />
<Button Margin="5,0,0,0" Width="70" Content="Disconnect" Command="{Binding DisconnectCommand}" />
</StackPanel>
</Grid>
<ListView Grid.Row="0" Grid.Column="1"
ItemsSource="{Binding Quotes}"
@@ -255,12 +230,18 @@
</Expander>
<StackPanel Grid.Row="1" Orientation="Vertical">
<Button Content="OrderSend" Command="{Binding OrderSendCommand}" Width="100" Height="25" HorizontalAlignment="Left" Margin="4"/>
<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"/>
<StackPanel Orientation="Horizontal">
<Button Content="OrderSend" Command="{Binding OrderSendCommand}" Width="100" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="OrderCheck" Command="{Binding OrderCheckCommand}" Width="100" Height="25" HorizontalAlignment="Left" Margin="4"/>
</StackPanel>
<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>
</Grid>
@@ -410,8 +391,8 @@
</TabItem>
</TabControl>
<Expander Grid.Row="2" Header="History" IsExpanded="True">
<ListBox mtApi5TestClient:ListBoxBehavior.ScrollOnNewItem="true" Height="200" ItemsSource="{Binding History}"/>
<Expander Grid.Row="2" Header="Console" IsExpanded="True">
<ListBox mtApi5TestClient:ListBoxBehavior.ScrollOnNewItem="true" Height="180" ItemsSource="{Binding History}"/>
</Expander>
<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.ComponentModel;
using System.Windows;
@@ -16,6 +17,8 @@ namespace MtApi5TestClient
public DelegateCommand DisconnectCommand { get; private set; }
public DelegateCommand OrderSendCommand { get; private set; }
public DelegateCommand OrderCheckCommand { get; private set; }
public DelegateCommand HistoryOrderGetIntegerCommand { get; private set; }
public DelegateCommand HistoryDealGetDoubleCommand { get; private set; }
public DelegateCommand HistoryDealGetIntegerCommand { get; private set; }
@@ -200,6 +203,8 @@ namespace MtApi5TestClient
DisconnectCommand = new DelegateCommand(ExecuteDisconnect, CanExecuteDisconnect);
OrderSendCommand = new DelegateCommand(ExecuteOrderSend);
OrderCheckCommand = new DelegateCommand(ExecuteOrderCheck);
HistoryOrderGetIntegerCommand = new DelegateCommand(ExecuteHistoryOrderGetInteger);
HistoryDealGetDoubleCommand = new DelegateCommand(ExecuteHistoryDealGetDouble);
HistoryDealGetIntegerCommand = new DelegateCommand(ExecuteHistoryDealGetInteger);
@@ -280,7 +285,22 @@ namespace MtApi5TestClient
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);
}
@@ -328,15 +348,14 @@ namespace MtApi5TestClient
{
try
{
var posId = await Execute(() => _mtApiClient.PositionGetInteger(ENUM_POSITION_PROPERTY_INTEGER.POSITION_IDENTIFIER)); // posId = 7247951
var history = await Execute(() => _mtApiClient.HistorySelectByPosition(posId)); // history = true
var historyDealsTotal = await Execute(() => _mtApiClient.HistoryDealsTotal()); // historyDealsCount = 4
var histDealTicket = await Execute(() => _mtApiClient.HistoryDealGetTicket(0)); // histDealTicket = 6632442
var histDealPrice = await Execute(() => _mtApiClient.HistoryDealGetDouble(histDealTicket, ENUM_DEAL_PROPERTY_DOUBLE.DEAL_PRICE)); // Exception
var posId = await Execute(() => _mtApiClient.PositionGetInteger(ENUM_POSITION_PROPERTY_INTEGER.POSITION_IDENTIFIER));
var history = await Execute(() => _mtApiClient.HistorySelectByPosition(posId));
var historyDealsTotal = await Execute(() => _mtApiClient.HistoryDealsTotal());
var histDealTicket = await Execute(() => _mtApiClient.HistoryDealGetTicket(0));
var histDealPrice = await Execute(() => _mtApiClient.HistoryDealGetDouble(histDealTicket, ENUM_DEAL_PROPERTY_DOUBLE.DEAL_PRICE));
}
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);
return;
}
@@ -969,20 +988,6 @@ namespace MtApi5TestClient
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()
{
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);
#import
#define __DEBUG_LOG__
//#define __DEBUG_LOG__
input int Port = 8228;
@@ -5588,6 +5588,9 @@ string OnRequest(string json)
case 4: //PositionOpen
response = ExecuteRequest_PositionOpen(jo);
break;
case 5: //OrderCheck
response = ExecuteRequest_OrderCheck(jo);
break;
default:
PrintFormat("%s [WARNING]: Unknown request type %d", __FUNCTION__, requestType);
response = CreateErrorResponse(-1, "Unknown request type");
@@ -5948,5 +5951,43 @@ string ExecuteRequest_PositionOpen(JSONObject *jo)
result_value_jo.put("RetVal", new JSONBool(ok));
result_value_jo.put("TradeResult", MqlTradeResultToJson(trade_result));
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);
}