Added projects MtApi4 and MtApi5

This commit is contained in:
Vyacheslav Demidyuk
2014-10-31 09:05:52 +02:00
parent 869d3a117b
commit 8746e96416
178 changed files with 26390 additions and 0 deletions
+43
View File
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestServer
{
enum CodeErrorTypes
{
ERR_NO_ERROR = 0,
ERR_NO_RESULT = 1,
ERR_COMMON_ERROR = 2,
ERR_INVALID_TRADE_PARAMETERS = 3,
ERR_SERVER_BUSY = 4,
ERR_OLD_VERSION = 5,
ERR_NO_CONNECTION = 6,
ERR_NOT_ENOUGH_RIGHTS = 7,
ERR_TOO_FREQUENT_REQUESTS = 8,
ERR_MALFUNCTIONAL_TRADE = 9,
ERR_ACCOUNT_DISABLED = 64,
ERR_INVALID_ACCOUNT = 65,
ERR_TRADE_TIMEOUT = 128,
ERR_INVALID_PRICE = 129,
ERR_INVALID_STOPS = 130,
ERR_INVALID_TRADE_VOLUME = 131,
ERR_MARKET_CLOSED = 132,
ERR_TRADE_DISABLED = 133,
ERR_NOT_ENOUGH_MONEY = 134,
ERR_PRICE_CHANGED = 135,
ERR_OFF_QUOTES = 136,
ERR_BROKER_BUSY = 137,
ERR_REQUOTE = 138,
ERR_ORDER_LOCKED = 139,
ERR_LONG_POSITIONS_ONLY_ALLOWED = 140,
ERR_TOO_MANY_REQUESTS = 141,
ERR_TRADE_MODIFY_DENIED = 145,
ERR_TRADE_CONTEXT_BUSY = 146,
ERR_TRADE_EXPIRATION_DENIED = 147,
ERR_TRADE_TOO_MANY_ORDERS = 148,
ERR_TRADE_HEDGE_PROHIBITED = 149,
ERR_TRADE_PROHIBITED_BY_FIFO = 150
}
}
+22
View File
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestServer
{
interface IMetaTrader
{
void Print(string msg);
void MessageBoxA(string msg);
string AccountName();
int AccountNumber();
bool IsDemo();
bool IsConnected();
string ErrorDescription(int errorCode);
int OrderSend(string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit
, string comment, int magic, int expiration, int arrow_color);
bool OrderClose(int ticket, double lots, double price, int slippage, int color);
}
}
+229
View File
@@ -0,0 +1,229 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TestServer
{
delegate void MetaTraderInfoHandler(string msg);
class MetaTrader: IMetaTrader, IDisposable
{
public MetaTrader(string accountName, int accountNumber)
{
mAccountName = accountName != null ? accountName : string.Empty;
mAccountNumber = accountNumber;
}
#region IMetaTrader
public void Print(string msg)
{
updateMetaTraderInfo(msg);
}
public void MessageBoxA(string msg)
{
updateMetaTraderInfo("[MessageBox] " + msg);
}
public string AccountName()
{
var msg = string.Format("MetaTrader: Commmand - AccountName");
updateMetaTraderInfo(msg);
return mAccountName;
}
public int AccountNumber()
{
var msg = string.Format("MetaTrader: Commmand - AccountNumber");
updateMetaTraderInfo(msg);
return mAccountNumber;
}
public bool IsDemo()
{
var msg = string.Format("MetaTrader: Commmand - IsDemo");
updateMetaTraderInfo(msg);
return mIsDemo;
}
public bool IsConnected()
{
var msg = string.Format("MetaTrader: Commmand - IsConnected");
updateMetaTraderInfo(msg);
return true;
}
public int OrderSend(string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit
, string comment, int magic, int expiration, int arrow_color)
{
var msg = string.Format("MetaTrader: Commmand - OrderSend: cmd = {0}, symbol = {1}, volume = {2}, price = {3}, slippage = {4}, stoploss = {5}, takeprofit = {6}, comment = {7}, magic = {8}, expiration = {9}, arrow_color = {10}"
, cmd, symbol, volume, price, slippage, stoploss, takeprofit, comment, magic, expiration, arrow_color);
updateMetaTraderInfo(msg);
Thread.Sleep(5000);
return ++mOrderCount;
}
public bool OrderClose(int ticket, double lots, double price, int slippage, int color)
{
var msg = string.Format("MetaTrader: Commmand - OrderClose, ticket = {0}, lots = {1}, price = {2}, slippage = {3}", ticket, lots, price, slippage);
updateMetaTraderInfo(msg);
return true;
}
public string ErrorDescription(int errorCode)
{
var msg = string.Format("MetaTrader: Commmand - ErrorDescription: errorCode = {0}", errorCode);
updateMetaTraderInfo(msg);
CodeErrorTypes errorType = (CodeErrorTypes)errorCode;
return errorType.ToString();
}
#endregion
#region Public Methods
public void Start()
{
foreach(var instrument in mInstruments)
{
instrument.Start();
}
mIsStarted = true;
}
public void Stop()
{
mIsStarted = false;
foreach (var chart in mInstrumentCharts)
{
chart.Stop();
}
foreach(var instrument in mInstruments)
{
instrument.Stop();
}
}
public void AddInstrument(MtInstrument instrument)
{
if (instrument != null && mInstruments.Contains(instrument) == false)
{
mInstruments.Add(instrument);
instrument.InstrumentUpdate += instrument_InstrumentUpdate;
if (mIsStarted == true)
instrument.Start();
}
}
public void RemoveInstrument(MtInstrument instrument)
{
if (instrument != null && mInstruments.Contains(instrument) == true)
{
mInstruments.Remove(instrument);
instrument.InstrumentUpdate -= instrument_InstrumentUpdate;
instrument.Stop();
}
}
public void AddInstrumentChart(MtInstrumentChart instrumentChart)
{
if (instrumentChart != null && mInstrumentCharts.Contains(instrumentChart) == false)
{
mInstrumentCharts.Add(instrumentChart);
instrumentChart.Start();
}
}
public void RemoveInstrumentChart(MtInstrumentChart instrumentChart)
{
if (instrumentChart != null && mInstrumentCharts.Contains(instrumentChart) == true)
{
mInstrumentCharts.Remove(instrumentChart);
instrumentChart.Stop();
}
}
public void SetDemo(bool isDemo)
{
mIsDemo = isDemo;
}
#endregion
#region Properties
public List<MtInstrument> Instruments
{
get { return mInstruments; }
}
public List<MtInstrumentChart> InstrumentCharts
{
get { return mInstrumentCharts; }
}
#endregion
#region Private Methods
void instrument_InstrumentUpdate(string symbol, double bid, double ask)
{
}
void updateMetaTraderInfo(string msg)
{
if (InfoUpdated != null)
InfoUpdated(msg);
}
#endregion
#region Events
public event MetaTraderInfoHandler InfoUpdated;
#endregion
#region Fields
private readonly string mAccountName;
private readonly int mAccountNumber;
private int mOrderCount = 0;
private readonly List<MtInstrument> mInstruments = new List<MtInstrument>();
private readonly List<MtInstrumentChart> mInstrumentCharts = new List<MtInstrumentChart>();
private bool mIsStarted = false;
private static List<string> OpTypes = new List<string> { "OP_BUY", "OP_SELL", "OP_BUYLIMIT", "OP_SELLLIMIT", "OP_BUYSTOP", "OP_SELLSTOP" };
private bool mIsDemo = true;
#endregion
#region IDisposable Members
public void Dispose()
{
}
#endregion
}
}
+145
View File
@@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestServer
{
enum MtExpertType
{
MtApiSymbol,
MtApiControl,
MtQuoteExpert
}
abstract class MtExpert
{
public MtExpert(MtExpertType expertType, IMetaTrader metatrader)
{
ExpertType = expertType;
mMetaTrader = metatrader;
}
#region Public Methods
public void Init()
{
Action a = () =>
{
mIsStartFuncBlocked = true;
init();
mIsStartFuncBlocked = false;
};
a.BeginInvoke(null, null);
}
public void Deinit()
{
Action a = () =>
{
deinit();
};
a.BeginInvoke(null, null);
}
public void Start()
{
Action a = () =>
{
if (mIsStartFuncBlocked == true)
return;
mIsStartFuncBlocked = true;
start();
mIsStartFuncBlocked = false;
};
a.BeginInvoke(null, null);
}
public void SetStopped()
{
mIsStopped = true;
}
public bool IsStopped()
{
return mIsStopped;
}
#endregion
#region Expert Methods
protected abstract void init();
protected abstract void deinit();
protected abstract void start();
#endregion
#region MetaTrader Functions
protected void Print(string msg)
{
if (mMetaTrader != null)
mMetaTrader.Print(msg);
}
protected void MessageBoxA(string msg)
{
if (mMetaTrader != null)
mMetaTrader.MessageBoxA(msg);
}
protected string AccountName()
{
return (mMetaTrader != null) ? mMetaTrader.AccountName() : string.Empty;
}
protected int AccountNumber()
{
return (mMetaTrader != null) ? mMetaTrader.AccountNumber() : -1;
}
protected bool IsDemo()
{
return (mMetaTrader != null) ? mMetaTrader.IsDemo() : false;
}
public bool IsConnected()
{
return (mMetaTrader != null) ? mMetaTrader.IsConnected() : false;
}
protected int OrderSend(string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit
, string comment, int magic, int expiration, int arrow_color)
{
return (mMetaTrader != null) ? mMetaTrader.OrderSend(symbol, cmd, volume, price, slippage, stoploss, takeprofit, comment, magic, expiration, arrow_color) : -1;
}
protected bool OrderClose(int ticket, double lots, double price, int slippage, int color)
{
return (mMetaTrader != null) ? mMetaTrader.OrderClose(ticket, lots, price, slippage, color) : false;
}
protected string ErrorDescription(int errorCode)
{
return (mMetaTrader != null) ? mMetaTrader.ErrorDescription(errorCode) : string.Empty;
}
#endregion
#region Properties
public MtExpertType ExpertType { get; private set; }
public string Symbol { get; set; }
public double Bid { get; set; }
public double Ask { get; set; }
#endregion
#region Fields
private readonly IMetaTrader mMetaTrader;
private volatile bool mIsStopped = false;
private volatile bool mIsStartFuncBlocked = false;
#endregion
}
}
+129
View File
@@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace TestServer
{
public delegate void InstrumentEventHandler(string symbol, double bid, double ask);
public class MtInstrument
{
public MtInstrument(string symbol, double startBid, double startAsk)
{
_symbol = symbol;
_bid = startBid;
_ask = startAsk;
}
private void work()
{
Debug.WriteLine(string.Format("[INFO] MetaTrader Instrument {0} is runned.", _symbol));
while (_isRunning)
{
if (_trendCycle <= 0)
{
Random randomCicle = new Random();
_trendCycle = randomCicle.Next(1, 10);
Random randomValue = new Random();
int tmpValue = randomValue.Next(1, 100);
_trend = (tmpValue > 50) ? 1 : -1;
}
Random randomCount = new Random();
int pipsCount = randomCount.Next(1, 4);
double change = (_trend * pipsCount * _pip);
lock (_lockPrice)
{
_bid += change;
_ask += change;
}
if (InstrumentUpdate != null)
InstrumentUpdate(_symbol, _bid, _ask);
_trendCycle--;
Random randomSleepValue = new Random();
int sleepValue = randomSleepValue.Next(200, 500);
Thread.Sleep(sleepValue);
}
Debug.WriteLine(string.Format("[INFO] MetaTrader Instrument {0} is stopepd.", _symbol));
}
public void Start()
{
_isRunning = true;
Thread thread = new Thread(work);
thread.Name = "Instrument_" + Symbol;
thread.Start();
}
public void Stop()
{
_isRunning = false;
}
public double Bid
{
get
{
lock (_lockPrice)
{
return _bid;
}
}
}
public double Ask
{
get
{
lock (_lockPrice)
{
return _ask;
}
}
}
public string Symbol
{
get
{
lock (_lockPrice)
{
return _symbol;
}
}
}
#region Events
public event InstrumentEventHandler InstrumentUpdate;
#endregion
#region Fields
private volatile bool _isRunning = false;
private int _trend = 1;
private int _trendCycle = 0;
private const double _pip = 0.0001;
private object _lockPrice = new object();
private double _bid;
private double _ask;
private string _symbol = string.Empty;
#endregion
}
}
+94
View File
@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestServer
{
class MtInstrumentChart
{
public MtInstrumentChart(MtInstrument instrument)
{
Instrument = instrument;
}
#region Public Methods
public void Start()
{
lock (mExpertLocker)
{
if (Expert != null)
{
if (Instrument != null)
Expert.Symbol = Instrument.Symbol;
Expert.Init();
}
}
if (Instrument != null)
{
Instrument.InstrumentUpdate += Instrument_InstrumentUpdate;
}
}
public void Stop()
{
if (Instrument != null)
{
Instrument.InstrumentUpdate -= Instrument_InstrumentUpdate;
}
lock (mExpertLocker)
{
if (Expert != null)
{
Expert.SetStopped();
Expert.Deinit();
}
}
}
public void AddExpert(MtExpert expert)
{
lock (mExpertLocker)
{
Expert = expert;
if (Expert != null)
{
if (Instrument != null)
Expert.Symbol = Instrument.Symbol;
Expert.Init();
}
}
}
#endregion
#region Private Methods
private void Instrument_InstrumentUpdate(string symbol, double bid, double ask)
{
lock (mExpertLocker)
{
if (Expert != null)
{
Expert.Symbol = symbol;
Expert.Bid = bid;
Expert.Ask = ask;
Expert.Start();
}
}
}
#endregion
#region Properties
public MtInstrument Instrument { get; private set; }
public MtExpert Expert { get; private set; }
private readonly object mExpertLocker = new object();
#endregion
}
}
+433
View File
@@ -0,0 +1,433 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
namespace TestServer
{
class MtQuoteExpert : MtExpert
{
#region Dll Import functions
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int initExpert(int isLocal, int port, [MarshalAs(UnmanagedType.LPStr)] string symbol, int expertHandle, IntPtr err);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int deinitExpert(int port, int expertHandle, IntPtr err);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int updateQuote(int port, [MarshalAs(UnmanagedType.LPStr)] string symbol, double bid, double ask, IntPtr err);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int getCommand(int port, ref int res, IntPtr err);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int getCommandType(int port, int commandId, ref int res);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int sendIntResponse(int port, int commandId, int response);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int sendBooleanResponse(int port, int commandId, int response);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int sendDoubleResponse(int port, int commandId, double response);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int sendVoidResponse(int port, int commandId);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int sendDoubleArrayResponse(int port, int commandId, int size);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int sendStringResponse(int port, int commandId, [MarshalAs(UnmanagedType.LPStr)]StringBuilder response);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int getIntValue(int port, int commandId, int paramIndex, ref int res);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int getDoubleValue(int port, int commandId, int paramIndex, ref double res);
//[DllImport(@"d:\dw\project\forex\MetaTraderApi\Debug\MTConnector.dll")]
[DllImport("MT5Connector.dll")]
public static extern int getStringValue(int port, int commandId, int paramIndex, IntPtr res);
#endregion
public MtQuoteExpert(IMetaTrader metatrader, int port, bool isController) :
base(MtExpertType.MtQuoteExpert, metatrader)
{
Port = port;
IsController = isController;
}
#region Public Methods
public override string ToString()
{
return string.Format("ExpertType = {0}; Port = {1}; IsController = {2}", ExpertType, Port, IsController);
}
#endregion
#region Protected Methods
protected override void init()
{
//int isDemo = IsDemo() == true ? 1 : 0;
int isDemo = 1;
mId = IDcount++;
int isLocal = 1;
if (initExpert(isLocal, Port, Symbol, mId, message) == 0)
{
MessageBoxA("Init error: " + "MetaTraderApi");
isCrashed = true;
return;
}
runController();
//if (IsController == true)
//{
// runController();
// if (deinitExpert(Port, mId, message) == 0)
// {
// MessageBoxA("Deinitilization error:\n" + "MetaTraderApi");
// return;
// }
//}
}
protected override void deinit()
{
if (isCrashed == false)
{
if (deinitExpert(Port, mId, message) == 0)
{
MessageBoxA("Deinit error: " + "MetaTraderApi");
isCrashed = true;
}
}
}
protected override void start()
{
if (isCrashed == false)
{
if (updateQuote(Port, Symbol, Bid, Ask, message) == 0)
{
MessageBoxA("Start error: " + "MetaTraderApi");
isCrashed = true;
}
}
}
#endregion
#region Private Methods
private void runController()
{
string symbolValue = string.Empty;
string commentValue = string.Empty;
string msgValue = string.Empty;
string captionValue = string.Empty;
string filenameValue = string.Empty;
string ftp_pathValue = string.Empty;
string subjectValue = string.Empty;
string some_textValue = string.Empty;
int cmdValue = -1;
int slippageValue = -1;
int ticketValue = -1;
int oppositeValue = -1;
int magicValue = -1;
int expirationValue = -1;
int arrow_colorValue = -1;
int colorValue = -1;
int indexValue = -1;
int selectValue = -1;
int poolValue = -1;
int errorCodeValue = -1;
int typeValue = -1;
int flagValue = -1;
int millisecondsValue = -1;
int dateValue = -1;
int timeValue = -1;
double lotsValue = double.NaN;
double volumeValue = double.NaN;
double priceValue = double.NaN;
double stoplossValue = double.NaN;
double takeprofitValue = double.NaN;
int a1 = IsDemo() == true ? 1 : 0;
Print("MetaTraderApi Expert is runned as controller. Symbol: " + Symbol);
while (!IsStopped())
{
Thread.Sleep(1000);
int commandId = -1;
if (getCommand(Port, ref commandId, message) == 0)
{
Print("[ERROR] getCommand");
isCrashed = true;
return;
}
//try
//{
// waitRequest(Port, ref commandId, message);
//}
//catch
//{
// Print("[ERROR] waitRequest");
// isCrashed = true;
// return;
//}
//if (waitRequest(Port, ref commandId, message) == 0)
//{
// Print("[ERROR] waitRequest");
// isCrashed = true;
// return;
//}
if (commandId < 0)
continue;
Print("MetaTraderApi Expert recieved command. Symbol: " + Symbol);
int commandType = 0;
if (getCommandType(Port, commandId, ref commandType) == 0)
{
Print("[ERROR] getCommandType");
continue;
}
switch (commandType)
{
case 0: //NoCommmand
break;
case 1: //OrderSend
{
//if (getStringValue(Port, mId, 0, ref symbolValue) == 0)
//{
// PrintParamError("symbolValue");
// return;
//}
if (getIntValue(Port, commandId, 1, ref cmdValue) == 0)
{
PrintParamError("cmd");
continue;
}
if (getDoubleValue(Port, commandId, 2, ref volumeValue) == 0)
{
PrintParamError("volume");
continue;
}
if (getDoubleValue(Port, commandId, 3, ref priceValue) == 0)
{
PrintParamError("price");
continue;
}
if (getIntValue(Port, commandId, 4, ref slippageValue) == 0)
{
PrintParamError("slippage");
continue;
}
if (getDoubleValue(Port, commandId, 5, ref stoplossValue) == 0)
{
PrintParamError("stoploss");
continue;
}
if (getDoubleValue(Port, commandId, 6, ref takeprofitValue) == 0)
{
PrintParamError("takeprofit");
continue;
}
//if (getStringValue(Port, mId, 7, ref commentValue) == 0)
//{
// PrintParamError("commentValue");
// return;
//}
if (getIntValue(Port, commandId, 8, ref magicValue) == 0)
{
PrintParamError("magic");
continue;
}
if (getIntValue(Port, commandId, 9, ref expirationValue) == 0)
{
PrintParamError("expiration");
continue;
}
if (getIntValue(Port, commandId, 10, ref arrow_colorValue) == 0)
{
PrintParamError("arrow_color");
continue;
}
if (sendIntResponse(Port, commandId, OrderSend(symbolValue, cmdValue, volumeValue, priceValue, slippageValue, stoplossValue, takeprofitValue, commentValue, magicValue, expirationValue, arrow_colorValue)) == 0)
{
PrintResponseError("OrderSend");
continue;
}
}
break;
//OrderClose
case 2:
{
if (getIntValue(Port, commandId, 0, ref ticketValue) == 0)
{
PrintParamError("ticket");
continue;
}
if (getDoubleValue(Port, commandId, 1, ref lotsValue) == 0)
{
PrintParamError("lots");
continue;
}
if (getDoubleValue(Port, commandId, 2, ref priceValue) == 0)
{
PrintParamError("price");
continue;
}
if (getIntValue(Port, commandId, 3, ref slippageValue) == 0)
{
PrintParamError("slippage");
continue;
}
if (getIntValue(Port, commandId, 4, ref colorValue) == 0)
{
PrintParamError("color");
continue;
}
//RefreshRates();
var result = OrderClose(ticketValue, lotsValue, priceValue, slippageValue, colorValue);
int responseValue = result == true ? 1 : 0;
if (sendBooleanResponse(Port, commandId, responseValue) == 0)
{
PrintResponseError("OrderClose");
continue;
}
}
break;
//IsConnected
case 27:
{
var result = IsConnected();
int responseValue = result == true ? 1 : 0;
if (sendBooleanResponse(Port, commandId, responseValue) == 0)
{
PrintResponseError("IsConnected");
continue;
}
}
break;
//IsDemo
case 28:
{
var result = true;// IsDemo();
int responseValue = result == true ? 1 : 0;
sendBooleanResponse(Port, commandId, responseValue);
}
break;
//ErrorDescription
case 39:
{
//int errorCode = getIntValueOfField(0);
//var result = ErrorDescription(errorCode);
//sendStringResponse(result);
}
break;
//iCloseArray
case 144:
{
int sizeValue = 0;
if (getIntValue(Port, commandId, 3, ref sizeValue) == 0)
{
PrintParamError("slippage");
continue;
}
if (sendDoubleArrayResponse(Port, commandId/*, prices*/, 100) == 0)
{
PrintResponseError("iCloseArray");
continue;
}
}
break;
default: //Unknown Commmand
Print(string.Format("MetaTrader: Unknown Commmand: code = {0}", commandType));
sendVoidResponse(Port, commandId);
break;
}
}
}
private void PrintParamError(string paramName)
{
Print("[ERROR] parameter: " + paramName);
}
private void PrintResponseError(string commandName)
{
Print("[ERROR] response: " + commandName);
}
#endregion
#region Properties
public int Port { get; private set; }
public bool IsController { get; private set; }
#endregion
#region Fields
private IntPtr message = IntPtr.Zero;
private bool isCrashed = false;
private int mId = -1;
private static int IDcount = 0;
#endregion
}
}
+243
View File
@@ -0,0 +1,243 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
namespace TestServer
{
class Program
{
static MetaTrader createMetaTrader(string accountName, int accountNumber)
{
MetaTrader mt = new MetaTrader(accountName, accountNumber);
mt.AddInstrument(new MtInstrument("EURUSD", 1.3, 1.4));
mt.AddInstrument(new MtInstrument("EURJPY", 1.3, 1.4));
mt.AddInstrument(new MtInstrument("EURAUD", 1.3, 1.4));
mt.AddInstrument(new MtInstrument("USDAUD", 1.3, 1.4));
mt.AddInstrument(new MtInstrument("USDJPY", 1.3, 1.4));
return mt;
}
static MtInstrument selectInstrument(List<MtInstrument> instruments)
{
MtInstrument result = null;
if (instruments != null)
{
Console.Clear();
Console.WriteLine("Select Instrument:");
foreach (var ins in instruments)
Console.WriteLine("{0} - {1}", instruments.IndexOf(ins), ins.Symbol);
string selectedIndexStr = Console.ReadLine();
int selectedIndex = -1;
int.TryParse(selectedIndexStr, out selectedIndex);
if (selectedIndex >= 0 && selectedIndex < instruments.Count)
{
result = instruments[selectedIndex];
}
else
{
Console.WriteLine("ERROR: Invalid number of Instrument!\nPress any key...");
}
}
return result;
}
static MtInstrumentChart selectChart(List<MtInstrumentChart> instrumentCharts)
{
MtInstrumentChart result = null;
if (instrumentCharts != null)
{
Console.WriteLine("Select Chart:");
foreach (var chart in instrumentCharts)
{
if (chart.Instrument != null)
{
Console.WriteLine("{0} - {1}", instrumentCharts.IndexOf(chart), chart.Instrument.Symbol);
}
}
string selectedIndexStr = Console.ReadLine();
int selectedIndex = -1;
int.TryParse(selectedIndexStr, out selectedIndex);
if (selectedIndex >= 0 && selectedIndex < instrumentCharts.Count)
{
result = instrumentCharts[selectedIndex];
}
else
{
Console.WriteLine("ERROR: Invalid number of Chart!\nPress any key...");
}
}
return result;
}
static void addChart(MetaTrader mt)
{
Console.Clear();
Console.WriteLine("Adding Chart.");
var selectedIinstrument = selectInstrument(mt.Instruments);
if (selectedIinstrument != null)
{
var instrumentChart = new MtInstrumentChart(selectedIinstrument);
mt.AddInstrumentChart(instrumentChart);
}
}
static void removeChart(MetaTrader mt)
{
var selectedChart = selectChart(mt.InstrumentCharts);
if (selectedChart != null)
{
mt.RemoveInstrumentChart(selectedChart);
}
}
static void addExpert(MetaTrader mt)
{
var selectedChart = selectChart(mt.InstrumentCharts);
if (selectedChart != null)
{
bool isController = false;
Console.WriteLine("Is Expert controller (y/n) ?");
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine();
switch (keyInfo.Key)
{
case ConsoleKey.N:
isController = false;
break;
case ConsoleKey.Y:
isController = true;
break;
}
Console.WriteLine("Input Port property (8222 - default): ");
string portStr = Console.ReadLine();
int port = 8222;
if (int.TryParse(portStr, out port) == false)
port = 8222;
var expert = new MtQuoteExpert(mt, port, isController);
if (expert != null)
{
selectedChart.AddExpert(expert);
}
}
}
static void printCharts(List<MtInstrumentChart> instrumentCharts)
{
if (instrumentCharts != null)
{
if (instrumentCharts.Count > 0)
{
Console.WriteLine("Working Charts:");
foreach (var chart in instrumentCharts)
{
if (chart.Instrument != null)
{
string chartInfo = chart.Instrument.Symbol;
if (chart.Expert != null)
{
chartInfo += " - ";
chartInfo += chart.Expert.ToString();
}
Console.WriteLine(chartInfo);
}
}
}
else
{
Console.WriteLine("No working Charts.");
}
Console.WriteLine();
}
}
static void Main(string[] args)
{
var mt = createMetaTrader("Vyacheslav Demidyuk", 9107044);
mt.SetDemo(false);
mt.InfoUpdated += new MetaTraderInfoHandler(mt_InfoUpdated);
mt.Start();
Console.WriteLine("Test Server of MetaTraderApi.");
Console.WriteLine("MetaTrader started.");
Console.WriteLine("Press any key to continue...\n");
Console.ReadKey();
bool isWorked = true;
do
{
Console.Clear();
printCharts(mt.InstrumentCharts);
Console.WriteLine("Choose command:");
Console.WriteLine("A- Add Chart");
Console.WriteLine("R- Remove Chart");
Console.WriteLine("E- Add Expert");
Console.WriteLine("Esc- Exit");
ConsoleKeyInfo keyInfo = Console.ReadKey();
switch (keyInfo.Key)
{
case ConsoleKey.A:
addChart(mt);
break;
case ConsoleKey.R:
removeChart(mt);
break;
case ConsoleKey.E:
addExpert(mt);
break;
case ConsoleKey.Escape:
isWorked = false;
break;
}
} while (isWorked);
Console.WriteLine("MetaTrader stopped.");
mt.Stop();
}
static void mt_InfoUpdated(string msg)
{
Console.WriteLine(msg);
}
}
}
+36
View File
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TestServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DW")]
[assembly: AssemblyProduct("TestServer")]
[assembly: AssemblyCopyright("Copyright © DW 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f96bb2dc-0e55-43e1-a5e4-7989310a09cc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+73
View File
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{220F01DF-8489-44F3-9C79-D5AFFCE94D6B}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TestServer</RootNamespace>
<AssemblyName>TestServer</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CodeErrorTypes.cs" />
<Compile Include="IMetaTrader.cs" />
<Compile Include="MtExpert.cs" />
<Compile Include="MtInstrument.cs" />
<Compile Include="MetaTrader.cs" />
<Compile Include="MtInstrumentChart.cs" />
<Compile Include="MtQuoteExpert.cs.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
+3
View File
@@ -0,0 +1,3 @@
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>