
Last Update: February 2, 2023 9 min read
BY
eric
cTrader FIX API in C# with QuickFIX/n: Logon, Quotes, Orders and Positions
Short version: use QuickFIX/n (the .NET FIX engine), open two FIX 4.4 sessions to cTrader (QUOTE for prices and symbols, TRADE for orders and positions), add your username and password to the Logon in ToAdmin, and call Crack() in FromApp so your OnMessage handlers actually run. Then deal with cTrader's quirks: symbols are numeric IDs, quantities are in units rather than lots, and on a hedging account you close a position by its position ID (tag 721), not by sending an opposite order.
This post is based on the FIX connector in my own data collector and trading gateway, a .NET 8 app using QuickFIXn 1.11.2. I got logon working on 23 January 2024, and it took until 21 February before opening and closing orders kept the position data correct. It then ran against several brokers' cTrader demo servers. The code below is simplified from that connector, and the errors in the tables come from its logs.
If you're new to the idea of a gateway between your strategy and the broker, start with Building an Efficient Gateway: Connecting Your Trading System to Brokers. Not every cTrader broker lets retail accounts use FIX. I've covered which ones do in cTrader FIX API: Which Brokers Say Yes to Retail Traders?.
An earlier version of this post had several code errors: an empty
FromApp(so no handler ever fired), wrongNewOrderSingleconstructors, closing positions withOrigClOrdID, and handlers for messages you never receive. They're fixed below.
What you need
- A cTrader account with FIX API enabled. Demo accounts are the place to start.
- .NET 8 (or whatever your project targets) and the QuickFIX/n packages.
- The FIX details from cTrader: Settings → FIX API in the cTrader app.
dotnet add package QuickFIXn.Core --version 1.11.2
dotnet add package QuickFIXn.FIX4.4 --version 1.11.2
cTrader speaks FIX 4.4, so you don't need the FIX 5.0 packages. I pinned 1.11.2 because that's what my project uses. Newer QuickFIX/n releases have changed some APIs, so if you upgrade, check the release notes.
Note: QuickFIX (no "/n") is the original C++ engine. QuickFIX/n is the separate .NET port. The earlier version of this post listed them as if both were C# options.
Get the FIX credentials from cTrader
In cTrader, go to Settings → FIX API. You get two blocks, one for the Price Connection and one for the Trade Connection:

For the demo account in this screenshot:
The same page also notes that cTrader accounts can be netting or hedging. That matters when you close positions (see below).
Use the SSL ports. The plain-text ports send your account password unencrypted. My demo configs used 5201 and 5202, which is fine for a demo, but don't do that on a live account.
One config file per channel
You need two sessions: QUOTE for market data and the symbol list, TRADE for orders, positions and execution reports. I keep a separate config file and a separate SocketInitiator for each. This is the quote one:
[DEFAULT]
ConnectionType=initiator
ReconnectInterval=30
FileStorePath=store
FileLogPath=log
StartTime=00:00:00
EndTime=00:00:00
HeartBtInt=30
UseDataDictionary=Y
DataDictionary=config/quickfix/MYFIX44.xml
AllowUnknownMsgFields=Y
ValidateFieldsOutOfOrder=N
ValidateFieldsHaveValues=N
ValidateUserDefinedFields=N
[SESSION]
BeginString=FIX.4.4
SocketConnectHost=demo2.p.ctrader.com
SocketConnectPort=5211
SSLEnable=Y
SSLServerName=demo2.p.ctrader.com
SenderCompID=YOUR_SENDER_COMP_ID
TargetCompID=cServer
SenderSubID=QUOTE
TargetSubID=QUOTE
The trade file is the same with port 5212 and TRADE for both sub IDs.
A few notes on the settings:
- Don't put the password in this file. Pass it in from an environment variable or secret store and add it in code (next section).
StartTimeandEndTimeboth00:00:00makes it a 24-hour session. FX servers run around the clock on weekdays.- The earlier version of this post had
AppDataDictionaryandTransportDataDictionary. Those are only for FIX 5.0 over FIXT.1.1 and do nothing on a FIX 4.4 session. It also had severalValidate...keys that aren't QuickFIX/n settings at all, so I've removed them.
Why a custom data dictionary
QuickFIX/n validates incoming messages against a data dictionary. cTrader's messages don't match the stock FIX44.xml exactly, so I copied it to MYFIX44.xml and edited it. The changes in mine:
- Made
ExecIDandAvgPxoptional in ExecutionReport, andRefMsgTypeoptional in BusinessMessageReject. - Made the
PositionQtygroup optional in PositionReport and movedPosTypeinside it. Before that I gotGroup 702's first entry does not start with delimiter 703errors. - Added
SymbolandMDEntryIDto the market data entry group, and madeMDEntryTypeandMDUpdateActionoptional there. - Defined tags 1007 and 1008 inside the Instrument component, because cTrader sends the symbol name and digits in those tags in the security list.
If you see "Tag not defined for this message type" or "Field not found" errors, the fix is usually in this file.
The application class
QuickFIX/n calls your IApplication for every message. Inheriting from MessageCracker lets you write one OnMessage overload per message type, but only if FromApp calls Crack(). With an empty FromApp nothing gets dispatched.
using QuickFix;
using QuickFix.Fields;
using QuickFix.Transport;
public class CTraderFixApp : MessageCracker, IApplication
{
private readonly string _username; // cTrader account number
private readonly string _password;
private int _seq = 0;
public SessionID? SessionId { get; private set; }
public CTraderFixApp(string username, string password)
{
_username = username;
_password = password;
}
// ClOrdID / request IDs must be unique. A plain counter restarts at 1
// when the process restarts, so prefix it with a timestamp.
public string NextId(string prefix) =>
$"{prefix}{DateTime.UtcNow:yyyyMMddHHmmss}-{Interlocked.Increment(ref _seq)}";
public void OnCreate(SessionID sessionID) => SessionId = sessionID;
public void OnLogon(SessionID sessionID) => Console.WriteLine($"Logon: {sessionID}");
public void OnLogout(SessionID sessionID) => Console.WriteLine($"Logout: {sessionID}");
public void ToAdmin(Message message, SessionID sessionID)
{
if (message is QuickFix.FIX44.Logon logon)
{
logon.Set(new Username(_username));
logon.Set(new Password(_password));
logon.Set(new ResetSeqNumFlag(true)); // start both sides at seq 1
}
}
public void FromAdmin(Message message, SessionID sessionID) { }
public void ToApp(Message message, SessionID sessionID)
{
// If QuickFIX/n is asked to resend old application messages after a
// reconnect, don't resend stale orders. It sends a gap fill instead.
if (message.Header.IsSetField(Tags.PossDupFlag) &&
message.Header.GetBoolean(Tags.PossDupFlag))
throw new DoNotSend();
}
public void FromApp(Message message, SessionID sessionID)
{
try
{
Crack(message, sessionID); // dispatches to the OnMessage overloads below
}
catch (UnsupportedMessageType)
{
Console.WriteLine($"No handler for: {message}");
}
}
public void Send(Message message)
{
if (SessionId is null) throw new InvalidOperationException("Not connected");
Session.SendToTarget(message, SessionId);
}
}
If you don't have an OnMessage overload for a message type the server sends, QuickFIX/n rejects it back to the server with "Unsupported Message Type". I hit that early on. The fix is to add an overload for every message type you expect, even if it only logs.
Watch your logs. The outgoing Logon contains your password in tag 554. The file log writes it in plain text, so protect the log folder or mask the field if you log messages yourself.
Starting both sessions
var user = Environment.GetEnvironmentVariable("CTRADER_ACCOUNT")!;
var pass = Environment.GetEnvironmentVariable("CTRADER_PASSWORD")!;
SocketInitiator Start(string cfgPath, IApplication app)
{
var settings = new SessionSettings(cfgPath);
var initiator = new SocketInitiator(
app,
new FileStoreFactory(settings),
settings,
new FileLogFactory(settings),
new DefaultMessageFactory());
initiator.Start();
return initiator;
}
var quoteApp = new CTraderFixApp(user, pass);
var tradeApp = new CTraderFixApp(user, pass);
var quote = Start("config/fix/quote.cfg", quoteApp);
var trade = Start("config/fix/trade.cfg", tradeApp);
// ... run until shutdown ...
quote.Stop();
trade.Stop();
The earlier version used ThreadedSocketInitiator. QuickFIX/n's initiator is SocketInitiator.
In practice you'll put the handlers for each channel in its own class, or one class with a channel flag like my connector. Don't fire requests from OnLogon before the other session is ready. My connector waits for the trade session to log on, asks for the security list, waits until it arrives (up to about 20 seconds), and only then requests positions and pending orders.
Symbols are numeric IDs
On cTrader FIX you never send "EURUSD". Every request uses a numeric symbol ID, which you get from a security list request on the QUOTE session:
// on the quote session
public void RequestSecurityList() =>
Send(new QuickFix.FIX44.SecurityListRequest(
new SecurityReqID(NextId("SL")),
new SecurityListRequestType(SecurityListRequestType.SYMBOL)));
public readonly Dictionary<string, string> IdToName = new();
public readonly Dictionary<string, string> NameToId = new();
public void OnMessage(QuickFix.FIX44.SecurityList msg, SessionID s)
{
int count = msg.GetInt(Tags.NoRelatedSym);
var group = new QuickFix.FIX44.SecurityList.NoRelatedSymGroup();
for (int i = 1; i <= count; i++) // FIX groups are 1-based
{
msg.GetGroup(i, group);
string id = group.GetString(Tags.Symbol); // e.g. "1"
string name = group.GetString(1007); // e.g. "EURUSD"
int digits = group.GetInt(1008); // price digits
IdToName[id] = name;
NameToId[name] = id;
}
}
Tags 1007 and 1008 only parse into the group if your data dictionary defines them there (see above). Keep these maps shared between the two sessions, because execution and position reports on the TRADE session also use the numeric IDs.
How many symbols you get depends on the broker. When I ran this against four brokers' cTrader servers in May 2024, the lists ranged from 77 to 1,000 symbols. There's a breakdown in Trading with cTrader as Your Trading Platform.
Market data
Subscribe on the QUOTE session with a MarketDataRequest:
public void Subscribe(string symbolId, string mdReqId)
{
var req = new QuickFix.FIX44.MarketDataRequest(
new MDReqID(mdReqId),
new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT_PLUS_UPDATES),
new MarketDepth(0)); // 0 = full depth; 1 = top of book (spot)
var types = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup();
types.Set(new MDEntryType(MDEntryType.BID));
req.AddGroup(types);
types = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup();
types.Set(new MDEntryType(MDEntryType.OFFER));
req.AddGroup(types);
var sym = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup();
sym.Set(new Symbol(symbolId));
req.AddGroup(sym); // one NoRelatedSymGroup per symbol
Send(req);
}
To unsubscribe, send the same request with SubscriptionRequestType.DISABLE_PREVIOUS_SNAPSHOT_PLUS_UPDATE_REQUEST. Keep the MDReqID you used for each symbol so you can reference it.
Three bugs from the earlier version, all worth checking in your own code:
AddGroupsets the group counts for you. SettingNoMDEntryTypesandNoRelatedSymby hand as well is unnecessary.- If you want several symbols in one request, add a separate
NoRelatedSymGroupfor each. CallingSet(new Symbol(...))repeatedly on one group just overwrites it, so only the last symbol gets subscribed. - The old handler had a
breakat the end of the loop, so it only read the first entry of each message. One incremental refresh can carry many entries.
My collector subscribes with MarketDepth(0) and reads the incremental refresh messages (35=X). With depth, each entry is a price level with an MDEntryID, and the update action says whether it's new or deleted. So keep a small book per symbol and take the best bid and ask from it:
// symbolId -> (MDEntryID -> (type, price))
private readonly Dictionary<string, Dictionary<string, (char Type, decimal Px)>> _books = new();
public void OnMessage(QuickFix.FIX44.MarketDataIncrementalRefresh msg, SessionID s)
{
int count = msg.GetInt(Tags.NoMDEntries);
var g = new QuickFix.FIX44.MarketDataIncrementalRefresh.NoMDEntriesGroup();
string symbolId = "";
for (int i = 1; i <= count; i++)
{
msg.GetGroup(i, g);
if (g.IsSetField(Tags.Symbol)) symbolId = g.GetString(Tags.Symbol);
if (!_books.TryGetValue(symbolId, out var book))
_books[symbolId] = book = new();
string entryId = g.IsSetField(Tags.MDEntryID) ? g.GetString(Tags.MDEntryID) : "";
char action = g.GetChar(Tags.MDUpdateAction);
if (action == MDUpdateAction.DELETE) { book.Remove(entryId); continue; }
book[entryId] = (g.GetChar(Tags.MDEntryType), g.GetDecimal(Tags.MDEntryPx));
}
foreach (var (id, book) in _books)
{
var bids = book.Values.Where(e => e.Type == MDEntryType.BID).ToList();
var asks = book.Values.Where(e => e.Type == MDEntryType.OFFER).ToList();
if (bids.Count == 0 || asks.Count == 0) continue; // need both for a spread
decimal bid = bids.Max(e => e.Px);
decimal ask = asks.Min(e => e.Px);
// publish (IdToName[id], bid, ask) to your strategy / data store
}
}
public void OnMessage(QuickFix.FIX44.MarketDataSnapshotFullRefresh msg, SessionID s)
{
// snapshots (35=W) arrive too, e.g. the initial snapshot; log them while testing
Console.WriteLine($"Snapshot: {msg}");
}
The "need both" check came from a real bug in my collector: I was computing spreads from a quote that only had one side.
Placing orders
Orders go on the TRADE session:
public string SendOrder(string symbolId, char side, decimal qty,
char ordType, decimal price = 0m, string? label = null)
{
string clOrdId = NextId("ORD");
var order = new QuickFix.FIX44.NewOrderSingle(
new ClOrdID(clOrdId),
new Symbol(symbolId), // numeric cTrader ID
new Side(side), // Side.BUY or Side.SELL (chars)
new TransactTime(DateTime.UtcNow), // FIX times are UTC
new OrdType(ordType)); // OrdType.MARKET, LIMIT or STOP
order.Set(new OrderQty(qty)); // in units, not lots
if (ordType == OrdType.LIMIT) order.Set(new Price(price));
else if (ordType == OrdType.STOP) order.Set(new StopPx(price));
if (label != null) order.Set(new Designation(label)); // tag 494
Send(order);
return clOrdId;
}
Things I learned the hard way:
- Quantity is in units, and limits are per symbol. Sending 0.10 as if it were lots fails with
TRADING_BAD_VOLUME: Order volume 0.10 is smaller than group minVolume=1000.00. My logs show minimums of 0.01, 1, 10, 50 and 5000 on different symbols, and maximums as low as 250. Check each symbol's volume limits and validate before sending. - Don't cast quantities to
int. My connector once did. Any fractional quantity became 0, and the broker rejected it with "Order volume 0.00 is smaller than group minVolume". StopPxis for stop orders, not a stop loss. A sell stop triggers when price falls toStopPx, and a buy stop when it rises to it. Sending aStopPxon a market order gets youINVALID_REQUEST: illegal value of stopPrice ... for MARKET order.- Stop-limit orders aren't supported.
OrdType=4came back asUnsupported OrdType(40)=4. - No take profit on the order. My connector's notes say cTrader's FIX API doesn't take one, so in my gateway the strategy watches the price and closes the position itself.
Designation(494) as a label. I put a strategy tag in it. It comes back on the execution report, so you can match fills to the strategy that sent them. Reports without it are orders the server generated.- The earlier version passed
OrderQty,Priceand a string side into the constructor. That doesn't compile:Sidetakes achar, and price and quantity are set separately.
Execution reports and rejects
Every order state change comes back as an ExecutionReport (35=8). Many cTrader errors come back as a BusinessMessageReject (35=j) with the reason in Text (58), so handle both:
public void OnMessage(QuickFix.FIX44.ExecutionReport er, SessionID s)
{
char execType = er.GetChar(Tags.ExecType);
char status = er.GetChar(Tags.OrdStatus);
string clOrdId = er.GetString(Tags.ClOrdID);
string orderId = er.GetString(Tags.OrderID);
string symbolId = er.GetString(Tags.Symbol);
string? positionId = er.IsSetField(Tags.PosMaintRptID)
? er.GetString(Tags.PosMaintRptID) : null; // save this: you close by it
if (status == OrdStatus.FILLED)
{
decimal fillPx = er.IsSetField(Tags.AvgPx) ? er.GetDecimal(Tags.AvgPx) : 0m;
decimal qty = er.IsSetField(Tags.OrderQty)
? er.GetDecimal(Tags.OrderQty) : er.GetDecimal(Tags.LastQty);
// update your order and position store
}
else if (status == OrdStatus.REJECTED)
{
string why = er.IsSetField(Tags.Text) ? er.GetString(Tags.Text) : "";
Console.WriteLine($"Rejected {clOrdId}: {why}");
}
// NEW (pending order accepted), CANCELED, EXPIRED, REPLACED: update state too.
// ExecType ORDER_STATUS ('I') is a reply to a status request, not a new event.
}
public void OnMessage(QuickFix.FIX44.BusinessMessageReject rej, SessionID s)
{
string reason = rej.IsSetField(Tags.Text) ? rej.GetString(Tags.Text) : "";
Console.WriteLine($"Business reject: {reason}");
}
Use IsSetField before reading optional fields. The old version read Price, LastPx and others unconditionally, which throws FieldNotFoundException on a market order fill.
Closing a position
The earlier version said to close a position by "just reversing the side". That's wrong on a hedging account: an opposite order without a position ID opens a new opposite position, and you end up with two. My connector code still has the comment where I found that out.
On cTrader you close a specific position by putting its ID in PosMaintRptID (721) on a NewOrderSingle with the opposite side:
public string ClosePosition(string positionId, string symbolId,
char positionSide, decimal qty)
{
char closeSide = positionSide == Side.BUY ? Side.SELL : Side.BUY;
string clOrdId = NextId("CLS");
var order = new QuickFix.FIX44.NewOrderSingle(
new ClOrdID(clOrdId),
new Symbol(symbolId),
new Side(closeSide),
new TransactTime(DateTime.UtcNow),
new OrdType(OrdType.MARKET));
order.Set(new OrderQty(qty));
order.SetField(new PosMaintRptID(positionId)); // which position to close
Send(order);
return clOrdId;
}
If the position is already gone, for example closed by a stop on the server, you get INCORRECT_POSITION_ID. My connector then drops that position from its cache and asks the server for positions again.
Positions and pending orders
When the gateway starts, or reconnects, it doesn't know what's open. Ask the server:
public void RequestPositions()
{
var req = new QuickFix.FIX44.RequestForPositions();
req.Set(new PosReqID(NextId("POS")));
Send(req);
}
public void OnMessage(QuickFix.FIX44.PositionReport rpt, SessionID s)
{
string positionId = rpt.GetString(Tags.PosMaintRptID);
string symbolId = rpt.IsSetField(Tags.Symbol) ? rpt.GetString(Tags.Symbol) : "";
var g = new QuickFix.FIX44.PositionReport.NoPositionsGroup();
rpt.GetGroup(1, g); // groups start at 1
decimal longQty = g.GetDecimal(Tags.LongQty);
decimal shortQty = g.GetDecimal(Tags.ShortQty);
decimal openPx = g.IsSetField(Tags.SettlPrice) ? g.GetDecimal(Tags.SettlPrice)
: rpt.IsSetField(Tags.SettlPrice) ? rpt.GetDecimal(Tags.SettlPrice) : 0m;
// upsert (positionId -> symbol, longQty, shortQty, openPx)
}
cTrader sends one PositionReport per position. TotalNumPosReports (727) is how many reports to expect, not how many groups are in this message. The old loop treated it as a group count and started at index 0, so it never read a position correctly. My connector reads group 1 of each report.
Treat the reports as a full snapshot. One of my early bugs added the reported quantity to my cached position on every refresh, so positions grew each time I checked. Mark everything in your cache as stale before the request, then keep only what comes back.
Pending (limit and stop) orders come from an OrderMassStatusRequest:
Send(new QuickFix.FIX44.OrderMassStatusRequest(
new MassStatusReqID(NextId("MS")),
new MassStatusReqType(MassStatusReqType.STATUS_FOR_ALL_ORDERS)));
Each pending order comes back as an ExecutionReport with ExecType=ORDER_STATUS. If there are none, you get a business reject with ORDER_NOT_FOUND:no orders found. That's not an error, so don't treat it as one. An early version of my code got stuck in a loop requesting pending orders.
Cancelling and modifying pending orders
To cancel, send an OrderCancelRequest with a new ClOrdID and the original order's IDs. This is the form my connector uses:
var cancel = new QuickFix.FIX44.OrderCancelRequest();
cancel.Set(new ClOrdID(NextId("CXL")));
cancel.Set(new OrigClOrdID(originalClOrdId));
cancel.Set(new OrderID(brokerOrderId));
Send(cancel);
FIX 4.4 also lists Symbol, Side and TransactTime as required, so add them if your server rejects the short form. To change price or quantity, use an OrderCancelReplaceRequest with the same IDs plus the new values.
The earlier version had OnMessage(OrderCancelRequest) and OnMessage(OrderCancelReplaceRequest) handlers for the confirmations. Those are messages you send, so they never arrive. The answer comes back as an ExecutionReport (ExecType CANCELED or REPLACED) or, if it fails, an OrderCancelReject (35=9).
cTrader FIX errors I hit and what they mean
What's next
Once the two sessions are stable, the rest is your gateway: send quotes to your strategies, accept order commands, and keep order and position state in sync with the server. The production lessons are similar to the ones in my MT5 Python gateway post: reconnect cleanly, re-sync positions after every reconnect, and never assume an order was filled until the execution report says so.
Credits
Photo by Shubham Dhage on Unsplash








Comments (0)
Leave a Comment