Topics
Replies
mindbreaker
08 Feb 2017, 17:06
Send socket
using FIX_API_Library;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FIX_API_Sample
{
public partial class frmFIXAPISample : Form
{
private int _pricePort = 5201;
private int _tradePort = 5202;
private string _host = "h20.p.ctrader.com";
private string _username = "9951960";
private string _password = "3604";
private string _senderCompID = "fxpro.9951960";
private string _senderSubID = "TRADE";
private string _targetCompID = "cSERVER";
private int _messageSequenceNumber = 1;
private int _testRequestID = 1;
TcpClient _priceClient;
NetworkStream _priceStream;
TcpClient _tradeClient;
NetworkStream _tradeStream;
MessageConstructor _messageConstructor;
public frmFIXAPISample()
{
InitializeComponent();
_priceClient = new TcpClient(_host, _pricePort);
_priceStream = _priceClient.GetStream();
_tradeClient = new TcpClient(_host, _tradePort);
_tradeStream = _priceClient.GetStream();
_messageConstructor = new MessageConstructor(_host, _username,
_password, _senderCompID, _senderSubID, _targetCompID);
}
private void ClearText()
{
txtMessageSend.Text = "";
txtMessageReceived.Text = "";
}
private string SendPriceMessage(string message)
{
return SendMessage(message, _priceStream);
}
private string SendTradeMessage(string message)
{
return SendMessage(message, _tradeStream);
}
private string SendMessage(string message, NetworkStream stream)
{
var byteArray = Encoding.ASCII.GetBytes(message);
stream.Write(byteArray, 0, byteArray.Length);
var buffer = new byte[1024];
int i = 0;
while (!stream.DataAvailable && i < 10)
{
Thread.Sleep(100);
i++;
}
if(stream.DataAvailable)
stream.Read(buffer, 0, 1024);
_messageSequenceNumber++;
var returnMessage = Encoding.ASCII.GetString(buffer);
return returnMessage;
}
private void btnLogon_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.LogonMessage(MessageConstructor.SessionQualifier.QUOTE, _messageSequenceNumber, 30, false);
txtMessageSend.Text = message;
txtMessageReceived.Text = SendPriceMessage(message);
}
private void btnTestRequest_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.TestRequestMessage(MessageConstructor.SessionQualifier.QUOTE, _messageSequenceNumber,_testRequestID);
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendPriceMessage(message);
}
private void btnLogout_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.LogoutMessage(MessageConstructor.SessionQualifier.QUOTE, _messageSequenceNumber);
txtMessageSend.Text = message;
txtMessageReceived.Text = SendPriceMessage(message);
_messageSequenceNumber = 1;
}
private void btnMarketDataRequest_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.MarketDataRequestMessage(MessageConstructor.SessionQualifier.QUOTE, _messageSequenceNumber, "EURUSD:WDqsoT", 1,0,0,1,1);
txtMessageSend.Text = message;
txtMessageReceived.Text = SendPriceMessage(message);
}
private void btnHeartbeat_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.HeartbeatMessage(MessageConstructor.SessionQualifier.QUOTE, _messageSequenceNumber);
txtMessageSend.Text = message;
txtMessageReceived.Text = SendPriceMessage(message);
}
private void btnResendRequest_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.ResendMessage(MessageConstructor.SessionQualifier.QUOTE, _messageSequenceNumber,_messageSequenceNumber - 1);
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendPriceMessage(message);
}
private void btnReject_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.RejectMessage(MessageConstructor.SessionQualifier.QUOTE, _messageSequenceNumber,0);
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendPriceMessage(message);
}
private void btnSequenceReset_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.SequenceResetMessage(MessageConstructor.SessionQualifier.QUOTE, _messageSequenceNumber,0);
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendPriceMessage(message);
}
private void btnNewOrderSingle_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.NewOrderSingleMessage(MessageConstructor.SessionQualifier.TRADE, _messageSequenceNumber,"1408471",1,1, DateTime.UtcNow.ToString("yyyyMMdd-HH:mm:ss"), 1000,1, "3");
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendTradeMessage(message);
}
private void btnOrderStatusRequest_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.OrderStatusRequest(MessageConstructor.SessionQualifier.TRADE, _messageSequenceNumber, "1408471");
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendTradeMessage(message);
}
private string Timestamp()
{
return (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds.ToString();
}
private void btnRequestForPositions_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.RequestForPositions(MessageConstructor.SessionQualifier.TRADE, _messageSequenceNumber, "876316401");
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendTradeMessage(message);
}
private void btnLogonT_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.LogonMessage(MessageConstructor.SessionQualifier.TRADE, _messageSequenceNumber, 30, false);
txtMessageSend.Text = message;
txtMessageReceived.Text = SendTradeMessage(message);
}
private void btnHeartbeatT_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.HeartbeatMessage(MessageConstructor.SessionQualifier.TRADE, _messageSequenceNumber);
txtMessageSend.Text = message;
txtMessageReceived.Text = SendTradeMessage(message);
}
private void btnTestRequestT_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.TestRequestMessage(MessageConstructor.SessionQualifier.TRADE, _messageSequenceNumber, _testRequestID);
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendTradeMessage(message);
}
private void btnLogoutT_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.LogoutMessage(MessageConstructor.SessionQualifier.TRADE, _messageSequenceNumber);
txtMessageSend.Text = message;
txtMessageReceived.Text = SendTradeMessage(message);
_messageSequenceNumber = 1;
}
private void btnResendRequestT_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.ResendMessage(MessageConstructor.SessionQualifier.TRADE, _messageSequenceNumber, _messageSequenceNumber - 1);
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendTradeMessage(message);
}
private void btnSpotMarketData_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.MarketDataRequestMessage(MessageConstructor.SessionQualifier.QUOTE, _messageSequenceNumber, "EURUSD:WDqsoT", 1, 1, 0, 1, 1);
txtMessageSend.Text = message;
txtMessageReceived.Text = SendPriceMessage(message);
}
private void btnStopOrder_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.NewOrderSingleMessage(MessageConstructor.SessionQualifier.TRADE, _messageSequenceNumber, "10", 1, 1, DateTime.UtcNow.ToString("yyyyMMdd-HH:mm:ss"), 1000, 3, "3",0, (decimal)1.08);
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendTradeMessage(message);
}
private void btnLimitOrder_Click(object sender, EventArgs e)
{
ClearText();
var message = _messageConstructor.NewOrderSingleMessage(MessageConstructor.SessionQualifier.TRADE, _messageSequenceNumber, "10", 1, 1, DateTime.UtcNow.ToString("yyyyMMdd-HH:mm:ss"), 1000,2, "3", (decimal)1.08);
_testRequestID++;
txtMessageSend.Text = message;
txtMessageReceived.Text = SendTradeMessage(message);
}
}
}
@mindbreaker
mindbreaker
08 Feb 2017, 17:04
FIX DLL
// Decompiled with JetBrains decompiler // Type: FIX_API_Library.MessageConstructor // Assembly: FIX API Library, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // Assembly location: C:\Users\KazikOratugorator\Desktop\FIX-API-Sample-master\FIX API Library.dll using System; using System.Text; namespace FIX_API_Library { public class MessageConstructor { private string _host; private string _username; private string _password; private string _senderCompID; private string _senderSubID; private string _targetCompID; public MessageConstructor(string host, string username, string password, string senderCompID, string senderSubID, string targetCompID) { this._host = host; this._username = username; this._password = password; this._senderCompID = senderCompID; this._senderSubID = senderSubID; this._targetCompID = targetCompID; } public string LogonMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, int heartBeatSeconds, bool resetSeqNum) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("98=0|"); stringBuilder.Append("108=" + (object) heartBeatSeconds + "|"); if (resetSeqNum) stringBuilder.Append("141=Y|"); stringBuilder.Append("553=" + this._username + "|"); stringBuilder.Append("554=" + this._password + "|"); string str1 = this.ConstructHeader(qualifier, this.SessionMessageCode(MessageConstructor.SessionMessageType.Logon), messageSequenceNumber, stringBuilder.ToString()); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string HeartbeatMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber) { string message = this.ConstructHeader(qualifier, this.SessionMessageCode(MessageConstructor.SessionMessageType.Heartbeat), messageSequenceNumber, string.Empty); string str = this.ConstructTrailer(message); return (message + str).Replace("|", "\x0001"); } public string TestRequestMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, int testRequestID) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("112=" + (object) testRequestID + "|"); string str1 = this.ConstructHeader(qualifier, this.SessionMessageCode(MessageConstructor.SessionMessageType.TestRequest), messageSequenceNumber, stringBuilder.ToString()); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string LogoutMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber) { string message = this.ConstructHeader(qualifier, this.SessionMessageCode(MessageConstructor.SessionMessageType.Logout), messageSequenceNumber, string.Empty); string str = this.ConstructTrailer(message); return (message + str).Replace("|", "\x0001"); } public string ResendMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, int endSequenceNo) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("16=" + (object) endSequenceNo + "|"); string str1 = this.ConstructHeader(qualifier, this.SessionMessageCode(MessageConstructor.SessionMessageType.Resend), messageSequenceNumber, stringBuilder.ToString()); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string RejectMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, int rejectSequenceNumber) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("45=" + (object) rejectSequenceNumber + "|"); string str1 = this.ConstructHeader(qualifier, this.SessionMessageCode(MessageConstructor.SessionMessageType.Reject), messageSequenceNumber, string.Empty); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string SequenceResetMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, int rejectSequenceNumber) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("36=" + (object) rejectSequenceNumber + "|"); string str1 = this.ConstructHeader(qualifier, this.SessionMessageCode(MessageConstructor.SessionMessageType.SequenceReset), messageSequenceNumber, string.Empty); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string MarketDataRequestMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, string marketDataRequestID, int subscriptionRequestType, int marketDepth, int marketDataEntryType, int noRelatedSymbol, long symbol = 0) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("262=" + marketDataRequestID + "|"); stringBuilder.Append("263=" + (object) subscriptionRequestType + "|"); stringBuilder.Append("264=" + (object) marketDepth + "|"); stringBuilder.Append("265=1|"); stringBuilder.Append("267=2|"); stringBuilder.Append("269=0|269=1|"); stringBuilder.Append("146=" + (object) noRelatedSymbol + "|"); stringBuilder.Append("55=" + (object) symbol + "|"); string str1 = this.ConstructHeader(qualifier, this.ApplicationMessageCode(MessageConstructor.ApplicationMessageType.MarketDataRequest), messageSequenceNumber, stringBuilder.ToString()); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string MarketDataSnapshotMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, long symbol, string noMarketDataEntries, int entryType, Decimal entryPrice, string marketDataRequestID = "") { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("262=" + marketDataRequestID + "|"); stringBuilder.Append("55=" + (object) symbol + "|"); stringBuilder.Append("268=" + noMarketDataEntries + "|"); stringBuilder.Append("269=" + (object) entryType + "|"); stringBuilder.Append("270=" + (object) entryPrice + "|"); string str1 = this.ConstructHeader(qualifier, this.ApplicationMessageCode(MessageConstructor.ApplicationMessageType.MarketDataRequest), messageSequenceNumber, stringBuilder.ToString()); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string MarketDataIncrementalRefreshMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, string marketDataRequestID, int noMarketDataEntries, int marketDataUpdateAction, int marketDataEntryType, string marketDataEntryID, int noRelatedSymbol, Decimal marketDataEntryPrice = 0M, double marketDataEntrySize = 0.0, long symbol = 0) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("262=" + marketDataRequestID + "|"); stringBuilder.Append("268=" + (object) noMarketDataEntries + "|"); stringBuilder.Append("279=" + (object) marketDataUpdateAction + "|"); stringBuilder.Append("269=" + (object) marketDataEntryType + "|"); stringBuilder.Append("278=" + marketDataEntryID + "|"); stringBuilder.Append("55=" + (object) symbol + "|"); if (marketDataEntryPrice > Decimal.Zero) stringBuilder.Append("270=" + (object) marketDataEntryPrice + "|"); if (marketDataEntrySize > 0.0) stringBuilder.Append("271=" + (object) marketDataEntrySize + "|"); string str1 = this.ConstructHeader(qualifier, this.ApplicationMessageCode(MessageConstructor.ApplicationMessageType.MarketDataIncrementalRefresh), messageSequenceNumber, string.Empty); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string NewOrderSingleMessage(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, string orderID, long symbol, int side, string transactTime, int orderQuantity, int orderType, string timeInForce, Decimal price = 0M, Decimal stopPrice = 0M, string expireTime = "", string positionID = "") { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("11=" + orderID + "|"); stringBuilder.Append("55=" + (object) symbol + "|"); stringBuilder.Append("54=" + (object) side + "|"); stringBuilder.Append("60=" + transactTime + "|"); stringBuilder.Append("38=" + (object) orderQuantity + "|"); stringBuilder.Append("40=" + (object) orderType + "|"); if (price != Decimal.Zero) stringBuilder.Append("44=" + (object) price + "|"); if (stopPrice != Decimal.Zero) stringBuilder.Append("99=" + (object) stopPrice + "|"); stringBuilder.Append("59=" + timeInForce + "|"); if (expireTime != string.Empty) stringBuilder.Append("126=" + expireTime + "|"); if (positionID != string.Empty) stringBuilder.Append("721=" + positionID + "|"); string str1 = this.ConstructHeader(qualifier, this.ApplicationMessageCode(MessageConstructor.ApplicationMessageType.NewOrderSingle), messageSequenceNumber, stringBuilder.ToString()); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string OrderStatusRequest(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, string orderID) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("11=" + orderID + "|"); stringBuilder.Append("54=1|"); string str1 = this.ConstructHeader(qualifier, this.ApplicationMessageCode(MessageConstructor.ApplicationMessageType.OrderStatusRequest), messageSequenceNumber, stringBuilder.ToString()); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string ExecutionReport(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, string cTraderOrderID, string orderStatus, string transactTime, long symbol = 0, int side = 1, int averagePrice = 0, int orderQuantity = 0, int leavesQuantity = 0, int cumQuantity = 0, string orderID = "", string orderType = "", int price = 0, int stopPrice = 0, string timeInForce = "", string expireTime = "", string text = "", int orderRejectionReason = -1, string positionID = "") { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("37=" + cTraderOrderID + "|"); stringBuilder.Append("11=" + orderID + "|"); stringBuilder.Append("150=F|"); stringBuilder.Append("39=" + orderStatus + "|"); stringBuilder.Append("55=" + (object) symbol + "|"); stringBuilder.Append("54=" + (object) side + "|"); stringBuilder.Append("60=" + transactTime + "|"); if (averagePrice > 0) stringBuilder.Append("6=" + (object) averagePrice + "|"); if (orderQuantity > 0) stringBuilder.Append("38=" + (object) orderQuantity + "|"); if (leavesQuantity > 0) stringBuilder.Append("151=" + (object) leavesQuantity + "|"); if (cumQuantity > 0) stringBuilder.Append("14=" + (object) cumQuantity + "|"); if (orderType != string.Empty) stringBuilder.Append("40=" + orderType + "|"); if (price > 0) stringBuilder.Append("44=" + (object) price + "|"); if (stopPrice > 0) stringBuilder.Append("99=" + (object) stopPrice + "|"); if (timeInForce != string.Empty) stringBuilder.Append("59=" + timeInForce + "|"); if (expireTime != string.Empty) stringBuilder.Append("126=" + expireTime + "|"); if (text != string.Empty) stringBuilder.Append("58=" + text + "|"); if (orderRejectionReason != -1) stringBuilder.Append("103=" + (object) orderRejectionReason + "|"); if (positionID != string.Empty) stringBuilder.Append("721=" + positionID + "|"); string str1 = this.ConstructHeader(qualifier, this.ApplicationMessageCode(MessageConstructor.ApplicationMessageType.OrderStatusRequest), messageSequenceNumber, stringBuilder.ToString()); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string BusinessMessageReject(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, int referenceSequenceNum = 0, string referenceMessageType = "", string businessRejectRefID = "", int businessRejectReason = -1, string text = "") { StringBuilder stringBuilder = new StringBuilder(); if ((uint) referenceSequenceNum > 0U) stringBuilder.Append("45=" + (object) referenceSequenceNum + "|"); if (referenceMessageType != string.Empty) stringBuilder.Append("372=" + referenceMessageType + "|"); if (businessRejectRefID != string.Empty) stringBuilder.Append("379=" + businessRejectRefID + "|"); if (businessRejectReason != -1) stringBuilder.Append("380=" + (object) businessRejectReason + "|"); if (text != string.Empty) stringBuilder.Append("58=" + text + "|"); string str1 = this.ConstructHeader(qualifier, this.ApplicationMessageCode(MessageConstructor.ApplicationMessageType.BusinessMessageReject), messageSequenceNumber, stringBuilder.ToString()); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string RequestForPositions(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, string requestID, string positionRequestID = "") { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("710=" + requestID + "|"); if (positionRequestID != string.Empty) stringBuilder.Append("721=" + positionRequestID + "|"); string str1 = this.ConstructHeader(qualifier, this.ApplicationMessageCode(MessageConstructor.ApplicationMessageType.RequestForPosition), messageSequenceNumber, stringBuilder.ToString()); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } public string PositionReport(MessageConstructor.SessionQualifier qualifier, int messageSequenceNumber, string requestID, string totalNumberOfPositionReports, string positionRequestResult, string positionID = "", string symbol = "", string noOfPositions = "", string longQuantity = "", string shortQuantity = "", string settlementPrice = "") { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("710=" + requestID + "|"); if (positionID != string.Empty) stringBuilder.Append("721=" + positionID + "|"); stringBuilder.Append("727=" + totalNumberOfPositionReports + "|"); stringBuilder.Append("728=" + positionRequestResult + "|"); if (symbol != string.Empty) stringBuilder.Append("55=" + symbol + "|"); if (noOfPositions != string.Empty) stringBuilder.Append("702=" + noOfPositions + "|"); if (longQuantity != string.Empty) stringBuilder.Append("704=" + requestID + "|"); if (shortQuantity != string.Empty) stringBuilder.Append("705=" + shortQuantity + "|"); if (settlementPrice != string.Empty) stringBuilder.Append("730=" + settlementPrice + "|"); string str1 = this.ConstructHeader(qualifier, this.ApplicationMessageCode(MessageConstructor.ApplicationMessageType.PositionReport), messageSequenceNumber, string.Empty); string str2 = this.ConstructTrailer(str1 + (object) stringBuilder); return (str1 + (object) stringBuilder + str2).Replace("|", "\x0001"); } private string ConstructHeader(MessageConstructor.SessionQualifier qualifier, string type, int messageSequenceNumber, string bodyMessage) { StringBuilder stringBuilder1 = new StringBuilder(); stringBuilder1.Append("8=FIX.4.4|"); StringBuilder stringBuilder2 = new StringBuilder(); stringBuilder2.Append("35=" + type + "|"); stringBuilder2.Append("49=" + this._senderCompID + "|"); stringBuilder2.Append("56=" + this._targetCompID + "|"); stringBuilder2.Append("57=" + qualifier.ToString() + "|"); stringBuilder2.Append("50=" + this._senderSubID + "|"); stringBuilder2.Append("34=" + (object) messageSequenceNumber + "|"); stringBuilder2.Append("52=" + DateTime.UtcNow.ToString("yyyyMMdd-HH:mm:ss") + "|"); int num = stringBuilder2.Length + bodyMessage.Length; stringBuilder1.Append("9=" + (object) num + "|"); stringBuilder1.Append((object) stringBuilder2); return stringBuilder1.Replace("|", "\x0001").ToString(); } private string ConstructTrailer(string message) { return ("10=" + (object) this.CalculateChecksum(message.Replace("|", "\x0001").ToString()) + "|").Replace("|", "\x0001"); } private int CalculateChecksum(string dataToCalculate) { byte[] bytes = Encoding.ASCII.GetBytes(dataToCalculate); int num1 = 0; foreach (byte num2 in bytes) num1 += (int) num2; return num1 % 256; } private string SessionMessageCode(MessageConstructor.SessionMessageType type) { switch (type) { case MessageConstructor.SessionMessageType.Logon: return "A"; case MessageConstructor.SessionMessageType.Logout: return "5"; case MessageConstructor.SessionMessageType.Heartbeat: return "0"; case MessageConstructor.SessionMessageType.TestRequest: return "1"; case MessageConstructor.SessionMessageType.Resend: return "2"; case MessageConstructor.SessionMessageType.Reject: return "3"; case MessageConstructor.SessionMessageType.SequenceReset: return "4"; default: return "0"; } } private string ApplicationMessageCode(MessageConstructor.ApplicationMessageType type) { switch (type) { case MessageConstructor.ApplicationMessageType.MarketDataRequest: return "V"; case MessageConstructor.ApplicationMessageType.MarketDataIncrementalRefresh: return "X"; case MessageConstructor.ApplicationMessageType.NewOrderSingle: return "D"; case MessageConstructor.ApplicationMessageType.OrderStatusRequest: return "H"; case MessageConstructor.ApplicationMessageType.ExecutionReport: return "8"; case MessageConstructor.ApplicationMessageType.BusinessMessageReject: return "j"; case MessageConstructor.ApplicationMessageType.RequestForPosition: return "AN"; case MessageConstructor.ApplicationMessageType.PositionReport: return "AP"; default: return "0"; } } public enum SessionMessageType { Logon, Logout, Heartbeat, TestRequest, Resend, Reject, SequenceReset, } public enum ApplicationMessageType { MarketDataRequest, MarketDataIncrementalRefresh, NewOrderSingle, OrderStatusRequest, ExecutionReport, BusinessMessageReject, RequestForPosition, PositionReport, } public enum SessionQualifier { QUOTE, TRADE, } } }
@mindbreaker
mindbreaker
08 Feb 2017, 15:23
Copex-FxStar Position Copier with SSL and MySQL or MariaDB (Internet network position duplication)
Hello ALL
Mysql based Position copier for cTrader and cAlgo
https://github.com/fxstar/Copex-FxStar
Copex-FxStar position copier
- Client - copy signals from Trader accounts.
- Allow multipy positions volume (from 0.1 to 1000000000).
- Allow positions StopLoss and TakeProfit (min. 10 Pips).
- Allow change timer to milliseconds (1 to 1000ms)
- Equity StopLoss (Close all positions and stop cBot)
- Mysql based (SSL allowed) you can copy from other locations hosts and IP.
Have a nice day
@mindbreaker
mindbreaker
08 Feb 2017, 15:08
( Updated at: 21 Dec 2023, 09:20 )
Spotware
Hello Spotware
Why example from Spotware github FIX-API-Sample https://github.com/spotware/FIX-API-Sample does not work on your own servers !!!!
@mindbreaker
mindbreaker
06 Feb 2017, 19:59
Symbol sym = MarketData.GetSymbol("EURUSD"); if ((Int32)vol < sym.VolumeMin || (Int32)vol > sym.VolumeMax){ Print("ERROR Position volume "); }
@mindbreaker
mindbreaker
03 Feb 2017, 23:31
cTrader, cAlgo copy positions
Hi All !
Thanks for the clarification.
Bye.
@mindbreaker
mindbreaker
09 Dec 2016, 11:51
Chart zoom on mouse wheel
And if it possible allow Chart zoom on mouse wheel ;)
@mindbreaker
mindbreaker
04 Oct 2016, 20:59
RE:
darhk said:
Hi Mindbreaker,
In your working logon code (post #17), were you able to get a logon message as a response after you send your logon message? I have similar code done in Python, but when I try to send my message, the FIX server disconnects me.
Thanks
try send this line it is correct msg:
8=FIX.4.4|9=108|35=A|34=1|49=fxpro.9910892|50=QUOTE|52=20161004-17:53:27.083|56=CSERVER|98=0|108=30|553=9910892|554=uthj1gv|10=069
and my demo test account
// cserver ip fix public static string host = "46.105.103.224"; // fix server id public static string FixID = "fxpro.9910892"; // ctrader account public static string Account = "9910892";
mayby will work (i dont want install python on my vps)
@mindbreaker
mindbreaker
04 Oct 2016, 20:47
RE:
darhk said:
Which sample are you referring to?
Ideally, I would like to avoid using a FIX engine (too much bloat) and C# as I am just want to collect market data on my Linux based server.
Hi
You can install .net core and try c# code on linux Server
https://www.microsoft.com/net/download
and try write in C# and run from command line
@mindbreaker
mindbreaker
28 Sep 2016, 11:07
where is error n this example
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.IO; using System.Security.Cryptography; namespace FixNoSSL { public class FixSocketClient { // cserver ip fix public static string host = "46.105.103.224"; // fix server id public static string FixID = "fxpro.9910892"; // ctrader account public static string Account = "9910892"; // ctrader password public static string Password = "ajdsakdhkash"; public static int total; public static string mm = ""; public static string md5(string input) { // step 1, calculate MD5 hash from input MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return sb.ToString(); } public static string SetTrade(int buy = 1, long lot = 1000, long symbol = 1) { string id = md5(DateTime.UtcNow.ToString()); string time = DateTime.UtcNow.ToString("yyyyMMdd-HH:mm:ss.fff"); string body = "35=D|49="+FixID+"|56=cServer|34=2|52="+time+"|11="+id+"|55="+symbol+"|54="+buy+"|60="+time+"|38="+lot+"|40=1|44=1.12473|59=3|"; // body length int bodylen = body.Length; string fix = "8=FIX.4.4|9=" + bodylen + "|"; // message string message = fix + body; message = message.Replace('|', '\u0001'); byte[] messageBytes = Encoding.ASCII.GetBytes(message); for (int i = 0; i < message.Length; i++) total += messageBytes[i]; int checksum = total % 256; string checksumStr = checksum.ToString().PadLeft(3, '0'); string sum = "10=" + checksumStr + "|"; string m = fix + body + sum; m = m.Replace('|', '\u0001'); return m; } public static string GetStatus(int buy = 1, long lot = 1000, long symbol = 1) { string id = md5(DateTime.UtcNow.ToString()); string time = DateTime.UtcNow.ToString("yyyyMMdd-HH:mm:ss.fff"); string body = "35=H|49=" + FixID + "|56=cServer|34=2|11=" + id + "|55=" + symbol + "|54=" + buy + "|"; // body length int bodylen = body.Length; string fix = "8=FIX.4.4|9=" + bodylen + "|"; // message string message = fix + body; message = message.Replace('|', '\u0001'); byte[] messageBytes = Encoding.ASCII.GetBytes(message); for (int i = 0; i < message.Length; i++) total += messageBytes[i]; int checksum = total % 256; string checksumStr = checksum.ToString().PadLeft(3, '0'); string sum = "10=" + checksumStr + "|"; string m = fix + body + sum; m = m.Replace('|', '\u0001'); return m; } public static void StartClient(string host) { string time = DateTime.UtcNow.ToString("yyyyMMdd-HH:mm:ss.fff"); string body = "35=A|34=1|49="+FixID+"|50=QUOTE|52=" + time + "|56=CSERVER|98=0|108=30|553="+Account+"|554="+Password+"|"; // body length int bodylen = body.Length; string fix = "8=FIX.4.4|9=" + bodylen + "|"; // message string message = fix + body; message = message.Replace('|', '\u0001'); byte[] messageBytes = Encoding.ASCII.GetBytes(message); for (int i = 0; i < message.Length; i++) total += messageBytes[i]; int checksum = total % 256; string checksumStr = checksum.ToString().PadLeft(3, '0'); string sum = "10=" + checksumStr + "|"; string m = fix + body + sum; m = m.Replace('|', '\u0001'); Console.WriteLine("Send to server (hit any key) {0}", m); Console.ReadKey(); mm = m; // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // Establish the remote endpoint for the socket. // This example uses port 11000 on the local computer. IPHostEntry ipHostInfo = Dns.GetHostEntry(host); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, 5202); // Create a TCP/IP socket. Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. Catch any errors. try { sender.Connect(remoteEP); Console.WriteLine("SOCKET CONECTED {0}", sender.RemoteEndPoint.ToString()); // Encode the data string into a byte array. byte[] msg = Encoding.ASCII.GetBytes(mm); // Send the data through the socket. int bytesSent = sender.Send(msg); // Receive the response from the remote device. int bytesRec = sender.Receive(bytes); Console.WriteLine("SERVER SEND >> {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec)); //string ms = SetTrade(1,1000,1); string ms = GetStatus(1, 1000, 1); string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); desktop = desktop + @"\cmd.txt"; File.WriteAllText(desktop,ms); Console.WriteLine("TRADE ADD "+ms); Console.ReadKey(); // Encode the data string into a byte array. byte[] msg1 = Encoding.ASCII.GetBytes(ms); // Send the data through the socket. int bytesSent1 = sender.Send(msg1); byte[] bytes1 = new byte[1024]; // Receive the response from the remote device. int bytesRec1 = sender.Receive(bytes1); Console.WriteLine("SERVER SEND (SET LOT) >> {0}", Encoding.ASCII.GetString(bytes1, 0, bytesRec1)); // Release the socket. sender.Shutdown(SocketShutdown.Both); sender.Close(); } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } public static int Main(String[] args) { while (true) { StartClient(host); Thread.Sleep(15000); } } } }
@mindbreaker
mindbreaker
28 Sep 2016, 11:03
How open new order
Hi
How open trade is it correct?
public static string SetTrade(int buy = 1, long lot = 1000, long symbol = 1) { string id = md5(DateTime.UtcNow.ToString()); string time = DateTime.UtcNow.ToString("yyyyMMdd-HH:mm:ss.fff"); string body = "35=D|49="+FixID+"|56=cServer|34=2|52="+time+"|11="+id+"|55="+symbol+"|54="+buy+"|60="+time+"|38="+lot+"|40=1|44=1.12473|59=3|"; // body length int bodylen = body.Length; string fix = "8=FIX.4.4|9=" + bodylen + "|"; // message string message = fix + body; message = message.Replace('|', '\u0001'); byte[] messageBytes = Encoding.ASCII.GetBytes(message); for (int i = 0; i < message.Length; i++) total += messageBytes[i]; int checksum = total % 256; string checksumStr = checksum.ToString().PadLeft(3, '0'); string sum = "10=" + checksumStr + "|"; string m = fix + body + sum; m = m.Replace('|', '\u0001'); return m; }
@mindbreaker
mindbreaker
28 Sep 2016, 09:58
Own smtp
iRobot said:
I know how to write the code, I don't know how to setup the Gmail for me to get the emails.
Hi
if you use VPS you can set your own SMTP:
look at this smpt server example (Windows vps)
https://www.youtube.com/watch?v=o-eMIxw4IjA
only couple minutes and you can send and recive emails. with your vps
OR
try this from google
http://stackoverflow.com/questions/20906077/gmail-error-the-smtp-server-requires-a-secure-connection-or-the-client-was-not
https://www.youtube.com/watch?v=y3cotIr41PQ
Bye.
@mindbreaker
mindbreaker
27 Sep 2016, 20:35
RE:
iRobot said:
I launched cAlgo from the VPS and did everything the same with the configuration to get my custom email alerts to Gmail like on PC. However, I don't receive any, only the error message:
Failed to send email "EURUSD Long M30 1,12063". System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at at System.Net.Mail.SendMailAsyncResult.End(IAsyncResult result) at System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result)
I approved the connection from the VPS in the Gmail, but it keeps blocking it.
How should I solve it?
Thanks
Hi try with this example:
https://github.com/fxstar/Chash/blob/master/SendEmailWithAttachments.cs
@mindbreaker
mindbreaker
22 Sep 2016, 10:41
RE: RE: RE: RE: RE:
Hi FIX working login example (NO SSL)
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace FixNoSSL { public class FixSocketClient { // cserver ip fix public static string host = "80.86.83.5"; // fix server id public static string FixID = "fxpro.123456"; // ctrader account public static string Account = "9910892"; // ctrader password public static string Password = "PASSWORD"; public static int total; public static string m = ""; public static void StartClient(string host) { string time = DateTime.UtcNow.ToString("yyyyMMdd-HH:mm:ss.fff"); string body = "35=A|34=1|49="+FixID+"|50=QUOTE|52=" + time + "|56=CSERVER|98=0|108=30|553="+Account+"|554="+Password+"|"; // body length int bodylen = body.Length; string fix = "8=FIX.4.4|9=" + bodylen + "|"; // message string message = fix + body; message = message.Replace('|', '\u0001'); byte[] messageBytes = Encoding.ASCII.GetBytes(message); for (int i = 0; i < message.Length; i++) total += messageBytes[i]; int checksum = total % 256; string checksumStr = checksum.ToString().PadLeft(3, '0'); string sum = "10=" + checksumStr + "|"; string m = fix + body + sum; m = m.Replace('|', '\u0001'); Console.WriteLine("Send to server (hit any key) {0}", m); Console.ReadKey(); // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // Establish the remote endpoint for the socket. // This example uses port 11000 on the local computer. IPHostEntry ipHostInfo = Dns.GetHostEntry(host); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, 5201); // Create a TCP/IP socket. Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. Catch any errors. try { sender.Connect(remoteEP); Console.WriteLine("SOCKET CONECTED {0}", sender.RemoteEndPoint.ToString()); // Encode the data string into a byte array. byte[] msg = Encoding.ASCII.GetBytes(m); // Send the data through the socket. int bytesSent = sender.Send(msg); // Receive the response from the remote device. int bytesRec = sender.Receive(bytes); Console.WriteLine("SERVER SEND >> {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec)); // Release the socket. sender.Shutdown(SocketShutdown.Both); sender.Close(); } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } public static int Main(String[] args) { while (true) { StartClient(host); Thread.Sleep(5000); } } } }
But whats after login how send message (some example)?
@mindbreaker
mindbreaker
17 Sep 2016, 16:16
RE:
Spotware said:
Hello mindbreaker,
Currently SSL is not being used for FIX connection. We understand the concern of yourself and your peers here in this forum and will address this situation as soon as we can.
Hi, Spotware
A few years ago I heard it.
Thanks and bye.
@mindbreaker
mindbreaker
13 Sep 2016, 11:40
Hi Spotware,
where is a simple example, how to send data to the server via FIX and how connect to the server over SSL socket?
What is wrong with my example ?
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; namespace FIX { class Program { public static string host = "h51.p.ctrader.com"; public static int total; static void Main(string[] args) { while (true) { StartClient(host); Thread.Sleep(5000); } } public static void StartClient(string host) { string time = DateTime.UtcNow.ToString("yyyyMMdd-hh:mm:ss.fff"); string body = "35=A|34=1|49=fxpro.9910892|554=PASSWORD|50=Quote|52=" + time + "|56=cServer|98=0|108=30|141=Y|553=1047|"; // body length int bodylen = body.Length; string fix = "8=FIX.4.4|9=" + bodylen + "|"; // message string message = fix + body; message = message.Replace('|', '\u0001'); byte[] messageBytes = Encoding.ASCII.GetBytes(message); for (int i = 0; i < message.Length; i++) total += messageBytes[i]; int checksum = total % 256; string checksumStr = checksum.ToString().PadLeft(3, '0'); string sum = "10=" + checksumStr + "|"; string m = fix + body + sum; m = m.Replace('|', '\u0001'); Console.WriteLine(m); Console.ReadKey(); // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { IPHostEntry ipHostInfo = Dns.GetHostEntry(host); IPAddress ipAddress = ipHostInfo.AddressList[0]; Console.WriteLine(ipAddress); TcpClient client = new TcpClient(host, 5201); SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); try { sslStream.AuthenticateAsClient(host); //sslStream.AuthenticateAsClientAsync(host); } catch (Exception e) { Console.WriteLine(e); client.Close(); return; } // Connect the socket to the remote endpoint. Catch any errors. try { //byte[] messsage = Encoding.UTF8.GetBytes("8=FIX.4.4|9=102|35=A|34=1|49=fxpro.9910892|50=Quote|52=20131129-15:40:10.276|56=cServer|98=0|108=30|141=Y|553=1047|554=PASSWORD|10=140|"); byte[] messsage = Encoding.UTF8.GetBytes(m); // Send hello message to the server. sslStream.Write(messsage); sslStream.Flush(); // Read message from the server. string serverMessage = ReadMessage(sslStream); Console.WriteLine("Server says: {0}", serverMessage); //Console.WriteLine("SERVER SEND: {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec)); } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } static string ReadMessage(SslStream sslStream) { byte[] buffer = new byte[2048]; StringBuilder messageData = new StringBuilder(); int bytes = -1; do { bytes = sslStream.Read(buffer, 0, buffer.Length); Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)]; decoder.GetChars(buffer, 0, bytes, chars, 0); messageData.Append(chars); Console.WriteLine(chars); // Check for EOF. if (messageData.ToString().IndexOf(" ") != -1) { break; } } while (bytes != 0); return messageData.ToString(); } // The following method is invoked by the RemoteCertificateValidationDelegate. public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; Console.WriteLine("Certificate error: {0}", sslPolicyErrors); // Do not allow this client to communicate with unauthenticated servers. //return false; //Force ssl certyfikates as correct return true; } } }
@mindbreaker
mindbreaker
13 Sep 2016, 11:33
FIX message
Hi, is it correct FIX message?
string time = DateTime.UtcNow.ToString("yyyyMMdd-hh:mm:ss.fff"); string body = "35=A|34=1|49=fxpro.9910892|554=PASSWORD|50=Quote|52=" + time + "|56=cServer|98=0|108=30|141=Y|553=1047|"; // body length int bodylen = body.Length; string fix = "8=FIX.4.4|9=" + bodylen + "|"; // message string message = fix + body; message = message.Replace('|', '\u0001'); byte[] messageBytes = Encoding.ASCII.GetBytes(message); for (int i = 0; i < message.Length; i++) total += messageBytes[i]; int checksum = total % 256; string checksumStr = checksum.ToString().PadLeft(3, '0'); string sum = "10=" + checksumStr + "|"; string m = fix + body + sum; Console.WriteLine(m);
Thanks
@mindbreaker
mindbreaker
08 Feb 2017, 17:06
@mindbreaker