Phase 3 needs books the bot can trust before any strategy trades. This adds: - schema 0003: executions, order events, trades, residues, account status, reconciliations, capital changes, applied corporate actions, simulator books; - the broker interface with the internal simulator and the Alpaca paper and OKX demo adapters, all behind the live guard (SPEC 2.2); - the append-only ledger with lots, trades from zero to zero, residues, dividends, splits and reversals; capital entrusted per broker and equity photographs with time-weighted return and FX effect; - the order manager (chasing limit, pacing, sells never abandoned, server stops, breached-stop rule) and the reconciler with prudent mode; - the trading service wired into the host, off in demo mode and in tests. Ids made with one clock in the same millisecond now carry a counter (RFC 9562 method 1): two lots of one order kept a random order, which broke LIFO. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
74d4c4fa6f
commit
1419457fe4
50 files changed
+7327
-5
No files matched your search
@@ -16,6 +16,15 @@ public sealed class CoreTests
|
||||
Assert.AreEqual(7, first.Version);
|
||||
Assert.IsLessThan(0, string.CompareOrdinal(first.ToString(), second.ToString()), "gli identificativi seguono il tempo");
|
||||
Assert.AreNotEqual(Ids.NewToken(), Ids.NewToken());
|
||||
|
||||
// In the same millisecond they still come out in order (two lots of one order, LIFO), with the clock's time.
|
||||
var burst = Enumerable.Range(0, 5000).Select(_ => Ids.NewId(clock).ToString()).ToList();
|
||||
CollectionAssert.AreEqual(burst.Order(StringComparer.Ordinal).ToList(), burst);
|
||||
Assert.AreEqual(burst.Count, burst.Distinct().Count());
|
||||
var time = Convert.ToInt64(burst[0].Replace("-", "", StringComparison.Ordinal)[..12], 16);
|
||||
Assert.AreEqual(clock.UtcNow.ToUnixTimeMilliseconds(), time);
|
||||
Assert.AreEqual(7, Guid.Parse(burst[^1]).Version);
|
||||
Assert.AreEqual(0x8, Guid.Parse(burst[^1]).Variant & 0xC);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"account_blocked": false,
|
||||
"account_number": "PALPACA_123",
|
||||
"accrued_fees": "0",
|
||||
"admin_configurations": {},
|
||||
"balance_asof": "2023-09-27",
|
||||
"buying_power": "245432.61",
|
||||
"cash": "122086.5",
|
||||
"created_at": "2023-01-01T18:20:20.272275Z",
|
||||
"crypto_status": "ACTIVE",
|
||||
"crypto_tier": 1,
|
||||
"currency": "USD",
|
||||
"effective_buying_power": "245432.61",
|
||||
"equity": "123346.11",
|
||||
"id": "1d9eed04-be39-4e01-9b84-a48ac5bbafcf",
|
||||
"initial_margin": "629.8",
|
||||
"intraday_adjustments": "0",
|
||||
"last_equity": "122011.09751111286868",
|
||||
"last_maintenance_margin": "480.73",
|
||||
"long_market_value": "1259.61",
|
||||
"maintenance_margin": "377.88",
|
||||
"multiplier": "2",
|
||||
"non_marginable_buying_power": "122086.5",
|
||||
"options_buying_power": "122716.305",
|
||||
"options_trading_level": 2,
|
||||
"pending_reg_taf_fees": "0",
|
||||
"pending_transfer_in": "0",
|
||||
"portfolio_value": "123346.11",
|
||||
"position_market_value": "1259.61",
|
||||
"regt_buying_power": "245432.61",
|
||||
"short_market_value": "0",
|
||||
"shorting_enabled": true,
|
||||
"sma": "123369.74",
|
||||
"status": "ACTIVE",
|
||||
"trade_suspended_by_user": false,
|
||||
"trading_blocked": false,
|
||||
"transfers_blocked": false,
|
||||
"user_configurations": null
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"activity_type": "DIV",
|
||||
"id": "20190801011955195::5f596936-6f23-4cef-bdf1-3806aae57dbf",
|
||||
"date": "2019-08-01",
|
||||
"net_amount": "1.02",
|
||||
"symbol": "T",
|
||||
"cusip": "C00206R102",
|
||||
"qty": "2",
|
||||
"per_share_amount": "0.51"
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"activity_type": "FILL",
|
||||
"cum_qty": "1",
|
||||
"id": "20190524113406977::8efc7b9a-8b2b-4000-9955-d36e7db0df74",
|
||||
"leaves_qty": "0",
|
||||
"price": "1.63",
|
||||
"qty": "1",
|
||||
"side": "buy",
|
||||
"symbol": "LPCN",
|
||||
"transaction_time": "2019-05-24T15:34:06.977Z",
|
||||
"order_id": "904837e3-3b76-47ec-b432-046db621571b",
|
||||
"type": "fill"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"code": 42210000,
|
||||
"message": "invalid limit_price 290.123. sub-penny increment does not fulfill minimum pricing criteria"
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"asset_class": "crypto",
|
||||
"asset_id": "a1733398-6acc-4e92-af24-0d0667f78713",
|
||||
"canceled_at": null,
|
||||
"client_order_id": "5b5d3d67-06ad-4ffa-af65-a117d0fc5a59",
|
||||
"created_at": "2023-12-12T22:36:51.337711497Z",
|
||||
"expired_at": null,
|
||||
"extended_hours": false,
|
||||
"failed_at": null,
|
||||
"filled_at": null,
|
||||
"filled_avg_price": null,
|
||||
"filled_qty": "0",
|
||||
"hwm": null,
|
||||
"id": "38e482f3-79a8-4f75-a057-f07a1ec6a397",
|
||||
"legs": null,
|
||||
"limit_price": "2100",
|
||||
"notional": null,
|
||||
"order_class": "",
|
||||
"order_type": "limit",
|
||||
"qty": "0.02",
|
||||
"replaced_at": null,
|
||||
"replaced_by": null,
|
||||
"replaces": null,
|
||||
"side": "buy",
|
||||
"source": null,
|
||||
"status": "pending_new",
|
||||
"stop_price": null,
|
||||
"submitted_at": "2023-12-12T22:36:51.313261061Z",
|
||||
"subtag": null,
|
||||
"symbol": "ETH/USD",
|
||||
"time_in_force": "gtc",
|
||||
"trail_percent": null,
|
||||
"trail_price": null,
|
||||
"type": "limit",
|
||||
"updated_at": "2023-12-12T22:36:51.337754768Z"
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"asset_class": "us_equity",
|
||||
"asset_id": "b0b6dd9d-8b9b-48a9-ba46-b9d54906e415",
|
||||
"canceled_at": null,
|
||||
"client_order_id": "5680c4bc-9ac1-4a12-a44c-df427ba53032",
|
||||
"created_at": "2023-12-12T22:31:24.668464435Z",
|
||||
"expired_at": null,
|
||||
"extended_hours": false,
|
||||
"failed_at": null,
|
||||
"filled_at": null,
|
||||
"filled_avg_price": null,
|
||||
"filled_qty": "0",
|
||||
"hwm": null,
|
||||
"id": "7b08df51-c1ac-453c-99f9-323a5f075f0d",
|
||||
"legs": null,
|
||||
"limit_price": "150",
|
||||
"notional": null,
|
||||
"order_class": "",
|
||||
"order_type": "limit",
|
||||
"qty": "2",
|
||||
"replaced_at": null,
|
||||
"replaced_by": null,
|
||||
"replaces": null,
|
||||
"side": "buy",
|
||||
"source": null,
|
||||
"status": "accepted",
|
||||
"stop_price": null,
|
||||
"submitted_at": "2023-12-12T22:31:24.577215743Z",
|
||||
"subtag": null,
|
||||
"symbol": "AAPL",
|
||||
"time_in_force": "gtc",
|
||||
"trail_percent": null,
|
||||
"trail_price": null,
|
||||
"type": "limit",
|
||||
"updated_at": "2023-12-12T22:31:24.668464435Z"
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"asset_class": "us_equity",
|
||||
"asset_id": "904837e3-3b76-47ec-b432-046db621571b",
|
||||
"asset_marginable": true,
|
||||
"avg_entry_price": "100.0",
|
||||
"change_today": "0.0084",
|
||||
"cost_basis": "500.0",
|
||||
"current_price": "120.0",
|
||||
"exchange": "NASDAQ",
|
||||
"lastday_price": "119.0",
|
||||
"market_value": "600.0",
|
||||
"qty": "5",
|
||||
"qty_available": "4",
|
||||
"side": "long",
|
||||
"symbol": "AAPL",
|
||||
"unrealized_intraday_pl": "10.0",
|
||||
"unrealized_intraday_plpc": "0.0084",
|
||||
"unrealized_pl": "100.0",
|
||||
"unrealized_plpc": "0.20"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"stream": "authorization",
|
||||
"data": {
|
||||
"status": "authorized",
|
||||
"action": "authenticate"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"stream": "trade_updates",
|
||||
"data": {
|
||||
"event": "fill",
|
||||
"execution_id": "2f63ea93-423d-4169-b3f6-3fdafc10c418",
|
||||
"order": {
|
||||
"asset_class": "crypto",
|
||||
"asset_id": "1cf35270-99ee-44e2-a77f-6fab902c7f80",
|
||||
"cancel_requested_at": null,
|
||||
"canceled_at": null,
|
||||
"client_order_id": "4642fd68-d59a-47d7-a9ac-e22f536828d1",
|
||||
"created_at": "2022-04-19T13:45:04.981350886-04:00",
|
||||
"expired_at": null,
|
||||
"extended_hours": false,
|
||||
"failed_at": null,
|
||||
"filled_at": "2022-04-19T17:45:05.024916716Z",
|
||||
"filled_avg_price": "105.8988475",
|
||||
"filled_qty": "1790.86",
|
||||
"hwm": null,
|
||||
"id": "a5be8f5e-fdfa-41f5-a644-7a74fe947a8f",
|
||||
"legs": null,
|
||||
"limit_price": null,
|
||||
"notional": null,
|
||||
"order_class": "",
|
||||
"order_type": "market",
|
||||
"qty": "1790.86",
|
||||
"replaced_at": null,
|
||||
"replaced_by": null,
|
||||
"replaces": null,
|
||||
"side": "sell",
|
||||
"status": "filled",
|
||||
"stop_price": null,
|
||||
"submitted_at": "2022-04-19T13:45:04.980944666-04:00",
|
||||
"symbol": "SOLUSD",
|
||||
"time_in_force": "gtc",
|
||||
"trail_percent": null,
|
||||
"trail_price": null,
|
||||
"type": "market",
|
||||
"updated_at": "2022-04-19T13:45:05.027690731-04:00"
|
||||
},
|
||||
"position_qty": "0",
|
||||
"price": "105.8988475",
|
||||
"qty": "1790.86",
|
||||
"timestamp": "2022-04-19T17:45:05.024916716Z"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"stream": "listening",
|
||||
"data": {
|
||||
"streams": ["trade_updates"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"code": "0",
|
||||
"data": [
|
||||
{
|
||||
"acctLv": "2",
|
||||
"acctStpMode": "cancel_maker",
|
||||
"autoLoan": false,
|
||||
"ctIsoMode": "automatic",
|
||||
"enableSpotBorrow": false,
|
||||
"greeksType": "PA",
|
||||
"feeType": "0",
|
||||
"ip": "",
|
||||
"type": "0",
|
||||
"kycLv": "3",
|
||||
"label": "v5 test",
|
||||
"level": "Lv1",
|
||||
"levelTmp": "",
|
||||
"liquidationGear": "-1",
|
||||
"mainUid": "44705892343619584",
|
||||
"mgnIsoMode": "automatic",
|
||||
"opAuth": "1",
|
||||
"perm": "read_only,withdraw,trade",
|
||||
"posMode": "long_short_mode",
|
||||
"roleType": "0",
|
||||
"spotBorrowAutoRepay": false,
|
||||
"spotOffsetType": "",
|
||||
"spotRoleType": "0",
|
||||
"spotTraderInsts": [],
|
||||
"stgyType": "0",
|
||||
"traderInsts": [],
|
||||
"uid": "44705892343619584",
|
||||
"settleCcy": "USDC",
|
||||
"settleCcyList": ["USD", "USDC", "USDG"]
|
||||
}
|
||||
],
|
||||
"msg": ""
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"code": "0",
|
||||
"data": [
|
||||
{
|
||||
"algoClOrdId": "",
|
||||
"algoId": "1836489397437468672",
|
||||
"clOrdId": "",
|
||||
"sCode": "0",
|
||||
"sMsg": "",
|
||||
"tag": ""
|
||||
}
|
||||
],
|
||||
"msg": ""
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"code": "0",
|
||||
"data": [
|
||||
{
|
||||
"algoClOrdId": "order1234",
|
||||
"algoId": "1836487817828872192",
|
||||
"clOrdId": "",
|
||||
"sCode": "0",
|
||||
"sMsg": "",
|
||||
"tag": ""
|
||||
}
|
||||
],
|
||||
"msg": ""
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"code": "0",
|
||||
"data": [
|
||||
{
|
||||
"activePx": "",
|
||||
"actualPx": "",
|
||||
"actualSide": "",
|
||||
"actualSz": "0",
|
||||
"algoClOrdId": "",
|
||||
"algoId": "1753184812254216192",
|
||||
"amendPxOnTriggerType": "0",
|
||||
"attachAlgoOrds": [],
|
||||
"cTime": "1724751378980",
|
||||
"callbackRatio": "",
|
||||
"callbackSpread": "",
|
||||
"ccy": "",
|
||||
"chaseType": "",
|
||||
"chaseVal": "",
|
||||
"clOrdId": "",
|
||||
"closeFraction": "",
|
||||
"failCode": "0",
|
||||
"instId": "BTC-USDT",
|
||||
"instType": "SPOT",
|
||||
"isTradeBorrowMode": "",
|
||||
"last": "62916.5",
|
||||
"lever": "",
|
||||
"linkedOrd": {
|
||||
"ordId": ""
|
||||
},
|
||||
"maxChaseType": "",
|
||||
"maxChaseVal": "",
|
||||
"moveTriggerPx": "",
|
||||
"ordId": "",
|
||||
"ordIdList": [],
|
||||
"ordPx": "",
|
||||
"ordType": "conditional",
|
||||
"posSide": "net",
|
||||
"pxLimit": "",
|
||||
"pxSpread": "",
|
||||
"pxVar": "",
|
||||
"quickMgnType": "",
|
||||
"reduceOnly": "false",
|
||||
"side": "buy",
|
||||
"slOrdPx": "",
|
||||
"slTriggerPx": "",
|
||||
"slTriggerPxType": "",
|
||||
"state": "live",
|
||||
"sz": "10",
|
||||
"szLimit": "",
|
||||
"tag": "",
|
||||
"tdMode": "cash",
|
||||
"tgtCcy": "quote_ccy",
|
||||
"timeInterval": "",
|
||||
"tpOrdPx": "-1",
|
||||
"tpTriggerPx": "10000",
|
||||
"tpTriggerPxType": "last",
|
||||
"triggerPx": "",
|
||||
"triggerPxType": "",
|
||||
"triggerTime": "",
|
||||
"tradeQuoteCcy": "USDT",
|
||||
"uTime": "1724751378980"
|
||||
}
|
||||
],
|
||||
"msg": ""
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"code": "0",
|
||||
"data": [
|
||||
{
|
||||
"adjEq": "55415.624719833286",
|
||||
"availEq": "55415.624719833286",
|
||||
"borrowFroz": "0",
|
||||
"delta": "0",
|
||||
"deltaLever": "0",
|
||||
"deltaNeutralStatus": "0",
|
||||
"details": [
|
||||
{
|
||||
"autoLendStatus": "off",
|
||||
"autoLendMtAmt": "0",
|
||||
"availBal": "4834.317093622894",
|
||||
"availEq": "4834.3170936228935",
|
||||
"borrowFroz": "0",
|
||||
"cashBal": "4850.435693622894",
|
||||
"ccy": "USDT",
|
||||
"crossLiab": "0",
|
||||
"colRes": "0",
|
||||
"collateralEnabled": false,
|
||||
"collateralRestrict": false,
|
||||
"colBorrAutoConversion": "0",
|
||||
"disEq": "4991.542013297616",
|
||||
"eq": "4992.890093622894",
|
||||
"eqUsd": "4991.542013297616",
|
||||
"smtSyncEq": "0",
|
||||
"spotCopyTradingEq": "0",
|
||||
"fixedBal": "0",
|
||||
"frozenBal": "158.573",
|
||||
"frpType": "0",
|
||||
"imr": "",
|
||||
"interest": "0",
|
||||
"isoEq": "0",
|
||||
"isoLiab": "0",
|
||||
"isoUpl": "0",
|
||||
"liab": "0",
|
||||
"maxLoan": "0",
|
||||
"mgnRatio": "",
|
||||
"mmr": "",
|
||||
"notionalLever": "",
|
||||
"ordFrozen": "0",
|
||||
"rewardBal": "0",
|
||||
"spotInUseAmt": "",
|
||||
"clSpotInUseAmt": "",
|
||||
"maxSpotInUse": "",
|
||||
"spotIsoBal": "0",
|
||||
"stgyEq": "150",
|
||||
"twap": "0",
|
||||
"uTime": "1705449605015",
|
||||
"upl": "-7.545600000000006",
|
||||
"uplLiab": "0",
|
||||
"spotBal": "",
|
||||
"openAvgPx": "",
|
||||
"accAvgPx": "",
|
||||
"spotUpl": "",
|
||||
"spotUplRatio": "",
|
||||
"totalPnl": "",
|
||||
"totalPnlRatio": ""
|
||||
}
|
||||
],
|
||||
"imr": "0",
|
||||
"isoEq": "0",
|
||||
"mgnRatio": "",
|
||||
"mmr": "0",
|
||||
"notionalUsd": "0",
|
||||
"notionalUsdForBorrow": "0",
|
||||
"notionalUsdForFutures": "0",
|
||||
"notionalUsdForOption": "0",
|
||||
"notionalUsdForSwap": "0",
|
||||
"ordFroz": "",
|
||||
"totalEq": "55837.43556134779",
|
||||
"uTime": "1705474164160",
|
||||
"upl": "0"
|
||||
}
|
||||
],
|
||||
"msg": ""
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"code": "0",
|
||||
"data": [
|
||||
{
|
||||
"side": "buy",
|
||||
"fillSz": "0.00192834",
|
||||
"fillPx": "51858",
|
||||
"fillPxVol": "",
|
||||
"fillFwdPx": "",
|
||||
"fee": "-0.00000192834",
|
||||
"fillPnl": "0",
|
||||
"ordId": "680800019749904384",
|
||||
"feeRate": "-0.001",
|
||||
"instType": "SPOT",
|
||||
"fillPxUsd": "",
|
||||
"instId": "BTC-USDT",
|
||||
"clOrdId": "",
|
||||
"posSide": "net",
|
||||
"billId": "680800019754098688",
|
||||
"subType": "1",
|
||||
"fillMarkVol": "",
|
||||
"tag": "",
|
||||
"fillTime": "1708587373361",
|
||||
"execType": "T",
|
||||
"fillIdxPx": "",
|
||||
"tradeId": "744876980",
|
||||
"fillMarkPx": "",
|
||||
"feeCcy": "BTC",
|
||||
"ts": "1708587373362",
|
||||
"tradeQuoteCcy": "USDT"
|
||||
}
|
||||
],
|
||||
"msg": ""
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"code":"0",
|
||||
"msg":"",
|
||||
"data":[
|
||||
{
|
||||
"clOrdId":"oktswap6",
|
||||
"ordId":"12345689",
|
||||
"ts":"1695190491421",
|
||||
"sCode":"0",
|
||||
"sMsg":""
|
||||
}
|
||||
],
|
||||
"inTime": "1695190491421339",
|
||||
"outTime": "1695190491423240"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"id": "1512",
|
||||
"op": "order",
|
||||
"data": [
|
||||
{
|
||||
"clOrdId": "",
|
||||
"ordId": "",
|
||||
"tag": "",
|
||||
"ts":"1695190491421",
|
||||
"sCode": "5XXXX",
|
||||
"sMsg": "not exist"
|
||||
}
|
||||
],
|
||||
"code": "1",
|
||||
"msg": "",
|
||||
"inTime": "1695190491421339",
|
||||
"outTime": "1695190491423240"
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"code": "0",
|
||||
"data": [
|
||||
{
|
||||
"accFillSz": "0.00192834",
|
||||
"algoClOrdId": "",
|
||||
"algoId": "",
|
||||
"attachAlgoClOrdId": "",
|
||||
"attachAlgoOrds": [],
|
||||
"avgPx": "51858",
|
||||
"cTime": "1708587373361",
|
||||
"cancelSource": "",
|
||||
"cancelSourceReason": "",
|
||||
"category": "normal",
|
||||
"ccy": "",
|
||||
"clOrdId": "",
|
||||
"fee": "-0.00000192834",
|
||||
"feeCcy": "BTC",
|
||||
"fillPx": "51858",
|
||||
"fillSz": "0.00192834",
|
||||
"fillTime": "1708587373361",
|
||||
"instId": "BTC-USDT",
|
||||
"instType": "SPOT",
|
||||
"isTpLimit": "false",
|
||||
"lever": "",
|
||||
"linkedAlgoOrd": {
|
||||
"algoId": ""
|
||||
},
|
||||
"ordId": "680800019749904384",
|
||||
"ordType": "market",
|
||||
"pnl": "0",
|
||||
"posSide": "net",
|
||||
"px": "",
|
||||
"pxType": "",
|
||||
"pxUsd": "",
|
||||
"pxVol": "",
|
||||
"quickMgnType": "",
|
||||
"rebate": "0",
|
||||
"rebateCcy": "USDT",
|
||||
"reduceOnly": "false",
|
||||
"side": "buy",
|
||||
"slOrdPx": "",
|
||||
"slTriggerPx": "",
|
||||
"slTriggerPxType": "",
|
||||
"source": "",
|
||||
"state": "filled",
|
||||
"stpId": "",
|
||||
"stpMode": "",
|
||||
"sz": "100",
|
||||
"tag": "",
|
||||
"tdMode": "cash",
|
||||
"tgtCcy": "quote_ccy",
|
||||
"tpOrdPx": "",
|
||||
"tpTriggerPx": "",
|
||||
"tpTriggerPxType": "",
|
||||
"tradeId": "744876980",
|
||||
"tradeQuoteCcy": "USDT",
|
||||
"uTime": "1708587373362"
|
||||
}
|
||||
],
|
||||
"msg": ""
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"code": "0",
|
||||
"msg": "",
|
||||
"data": [
|
||||
{
|
||||
"clOrdId": "oktswap6",
|
||||
"ordId": "312269865356374016",
|
||||
"tag": "",
|
||||
"ts":"1695190491421",
|
||||
"sCode": "0",
|
||||
"sMsg": "",
|
||||
"subCode": ""
|
||||
}
|
||||
],
|
||||
"inTime": "1695190491421339",
|
||||
"outTime": "1695190491423240"
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"code": "0",
|
||||
"data": [
|
||||
{
|
||||
"accFillSz": "0",
|
||||
"algoClOrdId": "",
|
||||
"algoId": "",
|
||||
"attachAlgoClOrdId": "",
|
||||
"attachAlgoOrds": [],
|
||||
"avgPx": "",
|
||||
"cTime": "1724733617998",
|
||||
"cancelSource": "",
|
||||
"cancelSourceReason": "",
|
||||
"category": "normal",
|
||||
"ccy": "",
|
||||
"clOrdId": "",
|
||||
"fee": "0",
|
||||
"feeCcy": "BTC",
|
||||
"fillPx": "",
|
||||
"fillSz": "0",
|
||||
"fillTime": "",
|
||||
"instId": "BTC-USDT",
|
||||
"instType": "SPOT",
|
||||
"isTpLimit": "false",
|
||||
"lever": "",
|
||||
"linkedAlgoOrd": {
|
||||
"algoId": ""
|
||||
},
|
||||
"ordId": "1752588852617379840",
|
||||
"ordType": "post_only",
|
||||
"pnl": "0",
|
||||
"posSide": "net",
|
||||
"px": "13013.5",
|
||||
"pxType": "",
|
||||
"pxUsd": "",
|
||||
"pxVol": "",
|
||||
"quickMgnType": "",
|
||||
"rebate": "0",
|
||||
"rebateCcy": "USDT",
|
||||
"reduceOnly": "false",
|
||||
"side": "buy",
|
||||
"slOrdPx": "",
|
||||
"slTriggerPx": "",
|
||||
"slTriggerPxType": "",
|
||||
"source": "",
|
||||
"state": "live",
|
||||
"stpId": "",
|
||||
"stpMode": "cancel_maker",
|
||||
"sz": "0.001",
|
||||
"tag": "",
|
||||
"tdMode": "cash",
|
||||
"tgtCcy": "",
|
||||
"tpOrdPx": "",
|
||||
"tpTriggerPx": "",
|
||||
"tpTriggerPxType": "",
|
||||
"tradeId": "",
|
||||
"tradeQuoteCcy": "USDT",
|
||||
"uTime": "1724733617998"
|
||||
}
|
||||
],
|
||||
"msg": ""
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"code": "0",
|
||||
"data": [
|
||||
{
|
||||
"category": "1",
|
||||
"delivery": "",
|
||||
"exercise": "",
|
||||
"feeGroup": [
|
||||
{
|
||||
"elpMaker": "-0.0008",
|
||||
"rpiMaker": "-0.0008",
|
||||
"groupId": "1",
|
||||
"maker": "-0.0008",
|
||||
"taker": "-0.001"
|
||||
}
|
||||
],
|
||||
"fiat": [],
|
||||
"instType": "SPOT",
|
||||
"level": "Lv1",
|
||||
"maker": "-0.0008",
|
||||
"makerU": "",
|
||||
"makerUSDC": "",
|
||||
"ruleType": "normal",
|
||||
"taker": "-0.001",
|
||||
"takerU": "",
|
||||
"takerUSDC": "",
|
||||
"ts": "1763979985847"
|
||||
}
|
||||
],
|
||||
"msg": ""
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"arg": {
|
||||
"channel": "orders-algo",
|
||||
"uid": "77982378738415879",
|
||||
"instType": "FUTURES",
|
||||
"instId": "BTC-USD-200329"
|
||||
},
|
||||
"data": [{
|
||||
"actualPx": "0",
|
||||
"actualSide": "",
|
||||
"actualSz": "0",
|
||||
"algoClOrdId": "",
|
||||
"algoId": "581878926302093312",
|
||||
"attachAlgoOrds": [],
|
||||
"amendResult": "",
|
||||
"cTime": "1685002746818",
|
||||
"uTime": "1708679675245",
|
||||
"ccy": "",
|
||||
"clOrdId": "",
|
||||
"closeFraction": "",
|
||||
"failCode": "",
|
||||
"instId": "BTC-USDC",
|
||||
"instType": "SPOT",
|
||||
"last": "26174.8",
|
||||
"lever": "0",
|
||||
"notionalUsd": "11.0",
|
||||
"ordId": "",
|
||||
"ordIdList": [],
|
||||
"ordPx": "",
|
||||
"ordType": "conditional",
|
||||
"posSide": "",
|
||||
"quickMgnType": "",
|
||||
"reduceOnly": "false",
|
||||
"reqId": "",
|
||||
"side": "buy",
|
||||
"slOrdPx": "",
|
||||
"slTriggerPx": "",
|
||||
"slTriggerPxType": "",
|
||||
"state": "live",
|
||||
"sz": "11",
|
||||
"tag": "",
|
||||
"tdMode": "cross",
|
||||
"tgtCcy": "quote_ccy",
|
||||
"tpOrdPx": "-1",
|
||||
"tpTriggerPx": "1",
|
||||
"tpTriggerPxType": "last",
|
||||
"triggerPx": "",
|
||||
"triggerTime": "",
|
||||
"tradeQuoteCcy": "USDT",
|
||||
"amendPxOnTriggerType": "0",
|
||||
"linkedOrd":{
|
||||
"ordId":"98192973880283"
|
||||
},
|
||||
"isTradeBorrowMode": ""
|
||||
}]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"event": "login",
|
||||
"code": "0",
|
||||
"msg": "",
|
||||
"connId": "a4d3ae55"
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
{
|
||||
"arg": {
|
||||
"channel": "orders",
|
||||
"instType": "SPOT",
|
||||
"instId": "BTC-USDT",
|
||||
"uid": "614488474791936"
|
||||
},
|
||||
"data": [
|
||||
{
|
||||
"accFillSz": "0.001",
|
||||
"algoClOrdId": "",
|
||||
"algoId": "",
|
||||
"amendResult": "",
|
||||
"amendSource": "",
|
||||
"avgPx": "31527.1",
|
||||
"cancelSource": "",
|
||||
"category": "normal",
|
||||
"ccy": "",
|
||||
"clOrdId": "",
|
||||
"code": "0",
|
||||
"cTime": "1654084334977",
|
||||
"execType": "M",
|
||||
"fee": "-0.02522168",
|
||||
"feeCcy": "USDT",
|
||||
"fillFee": "-0.02522168",
|
||||
"fillFeeCcy": "USDT",
|
||||
"fillNotionalUsd": "31.50818374",
|
||||
"fillPx": "31527.1",
|
||||
"fillSz": "0.001",
|
||||
"fillPnl": "0.01",
|
||||
"fillTime": "1654084353263",
|
||||
"fillPxVol": "",
|
||||
"fillPxUsd": "",
|
||||
"fillMarkVol": "",
|
||||
"fillFwdPx": "",
|
||||
"fillMarkPx": "",
|
||||
"fillIdxPx": "",
|
||||
"instId": "BTC-USDT",
|
||||
"instType": "SPOT",
|
||||
"lever": "0",
|
||||
"msg": "",
|
||||
"notionalUsd": "31.50818374",
|
||||
"ordId": "452197707845865472",
|
||||
"ordType": "limit",
|
||||
"pnl": "0",
|
||||
"posSide": "",
|
||||
"px": "31527.1",
|
||||
"pxUsd":"",
|
||||
"pxVol":"",
|
||||
"pxType":"",
|
||||
"quickMgnType": "",
|
||||
"rebate": "0",
|
||||
"rebateCcy": "BTC",
|
||||
"reduceOnly": "false",
|
||||
"reqId": "",
|
||||
"side": "sell",
|
||||
"attachAlgoClOrdId": "",
|
||||
"slOrdPx": "",
|
||||
"slTriggerPx": "",
|
||||
"slTriggerPxType": "last",
|
||||
"source": "",
|
||||
"state": "filled",
|
||||
"stpId": "",
|
||||
"stpMode": "",
|
||||
"sz": "0.001",
|
||||
"tag": "",
|
||||
"tdMode": "cash",
|
||||
"tgtCcy": "",
|
||||
"tpOrdPx": "",
|
||||
"tpTriggerPx": "",
|
||||
"tpTriggerPxType": "last",
|
||||
"attachAlgoOrds": [],
|
||||
"tradeId": "242589207",
|
||||
"tradeQuoteCcy": "USDT",
|
||||
"lastPx": "38892.2",
|
||||
"uTime": "1654084353264",
|
||||
"isTpLimit": "false",
|
||||
"riskBypassResult": "",
|
||||
"linkedAlgoOrd": {
|
||||
"algoId": ""
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"id": "1512",
|
||||
"event": "subscribe",
|
||||
"arg": {
|
||||
"channel": "orders",
|
||||
"instType": "FUTURES",
|
||||
"instId": "BTC-USD-200329"
|
||||
},
|
||||
"connId": "a4d3ae55"
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>The bot's books (issue #29, SPEC 7.5): append-only rows, lots, trades from zero to zero, equity, returns.</summary>
|
||||
[TestClass]
|
||||
public sealed class LedgerTests
|
||||
{
|
||||
private static readonly CancellationToken _none = CancellationToken.None;
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task BuyAndSellMakeATradeFromZeroToZeroWithFeesAndResult()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
var account = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false);
|
||||
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
|
||||
const string strategy = Strategies.EquityMomentum;
|
||||
await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 10000m, "USD", "test", _none).ConfigureAwait(false);
|
||||
|
||||
var first = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Buy, 10m, 400m, 0.03m) with { ReferencePrice = 399.8m }, _none).ConfigureAwait(false);
|
||||
Assert.IsTrue(first.Recorded);
|
||||
Assert.AreEqual(10m, first.Quantity);
|
||||
Assert.AreEqual(400.003m, first.AveragePrice, "The fee is part of the cost.");
|
||||
Assert.AreEqual(Math.Round(0.2m / 399.8m * 10000m, 6), Math.Round(first.SlippageBp!.Value, 6), "Slippage against the reference, in basis points.");
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Buy, 5m, 412m), _none).ConfigureAwait(false);
|
||||
|
||||
// A partial sale enters the realised result at once; the trade stays open.
|
||||
var partial = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Sell, 6m, 420m, 0.06m), _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(9m, partial.Quantity);
|
||||
Assert.IsFalse(partial.TradeClosed);
|
||||
var last = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Sell, 9m, 430m, 0.09m) with { ExitReason = "stop" }, _none).ConfigureAwait(false);
|
||||
Assert.IsTrue(last.TradeClosed);
|
||||
Assert.AreEqual(0m, last.Quantity);
|
||||
Assert.IsNull(await rig.Ledger.PositionAsync(account.AccountId, msft.Id, strategy, _none).ConfigureAwait(false), "A closed position is gone.");
|
||||
|
||||
var trade = (await rig.QueryAsync("SELECT status, bought_quantity, sold_quantity, fees, realized, exit_reason FROM trades",
|
||||
r => (Status: r.Text("status"), Bought: r.Money("bought_quantity"), Sold: r.Money("sold_quantity"), Fees: r.Money("fees"), Realized: r.Money("realized"), Exit: r.TextOrNull("exit_reason")))
|
||||
.ConfigureAwait(false)).Single();
|
||||
Assert.AreEqual(("closed", 15m, 15m, 0.18m, "stop"), (trade.Status, trade.Bought, trade.Sold, trade.Fees, trade.Exit));
|
||||
|
||||
// Net result: money in minus money out, fees included.
|
||||
var expected = (6m * 420m) + (9m * 430m) - (10m * 400m) - (5m * 412m) - 0.18m;
|
||||
Assert.AreEqual(expected, trade.Realized);
|
||||
var equity = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single();
|
||||
Assert.AreEqual(10000m + expected, equity.Equity);
|
||||
Assert.AreEqual(expected, equity.Result);
|
||||
|
||||
// The same execution twice is recorded once (duplicate fills, SPEC 7.4).
|
||||
var fill = rig.Fill(account, msft, strategy, OrderSide.Buy, 1m, 400m);
|
||||
Assert.IsTrue((await rig.Ledger.RecordFillAsync(fill, _none).ConfigureAwait(false)).Recorded);
|
||||
Assert.IsFalse((await rig.Ledger.RecordFillAsync(fill, _none).ConfigureAwait(false)).Recorded);
|
||||
Assert.AreEqual(1m, (await rig.Ledger.PositionAsync(account.AccountId, msft.Id, strategy, _none).ConfigureAwait(false))!.Quantity);
|
||||
|
||||
// Never sells what the strategy does not hold.
|
||||
await Assert.ThrowsExactlyAsync<LedgerException>(() => rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Sell, 2m, 400m), _none)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task FeesTakenInTheCoinReduceTheQuantityAndLotsFollowTheTaxMethod()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
|
||||
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
|
||||
const string strategy = Strategies.CryptoTrend;
|
||||
await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 5000m, "EUR", "test", _none).ConfigureAwait(false);
|
||||
|
||||
// OKX keeps the fee of a purchase in the bought coin (SPEC 4.2): 0.01 bought, 0.00001 kept.
|
||||
var buy = await rig.Ledger.RecordFillAsync(rig.Fill(account, btc, strategy, OrderSide.Buy, 0.01m, 60000m, 0.00001m, "BTC"), _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(0.00999m, buy.Quantity);
|
||||
Assert.AreEqual(Math.Round(600m / 0.00999m, 10), Math.Round(buy.AveragePrice, 10));
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(account, btc, strategy, OrderSide.Buy, 0.01m, 62000m, 0.00001m, "BTC"), _none).ConfigureAwait(false);
|
||||
|
||||
// LIFO (default): the newest lot leaves first.
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(account, btc, strategy, OrderSide.Sell, 0.005m, 63000m, 0.63m, "EUR"), _none).ConfigureAwait(false);
|
||||
var lots = await rig.Ledger.OpenLotsAsync(account.AccountId, btc.Id, strategy, _none).ConfigureAwait(false);
|
||||
Assert.HasCount(2, lots);
|
||||
Assert.AreEqual(0.00499m, lots.Single(l => l.Price > 61000m).Remaining);
|
||||
Assert.AreEqual(0.00999m, lots.Single(l => l.Price < 61000m).Remaining);
|
||||
|
||||
var fifo = new Ledger(rig.Db, rig.Clock) { LotMethod = LotMethod.Fifo };
|
||||
var ordered = await fifo.OpenLotsAsync(account.AccountId, btc.Id, strategy, _none).ConfigureAwait(false);
|
||||
Assert.IsLessThan(ordered[1].Price, ordered[0].Price, "FIFO lists the oldest lot first.");
|
||||
|
||||
var position = await rig.Ledger.PositionAsync(account.AccountId, btc.Id, strategy, _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(0.01498m, position!.Quantity);
|
||||
Assert.AreEqual(position.Quantity, lots.Sum(l => l.Remaining), "Lots and position always agree.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ResiduesDividendsSplitsAndReversalsKeepTheBooksRight()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
var okx = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
|
||||
var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false);
|
||||
var pepe = await rig.InstrumentAsync(TradingRig.Pepe).ConfigureAwait(false);
|
||||
var aapl = await rig.InstrumentAsync(TradingRig.Stock("AAPL")).ConfigureAwait(false);
|
||||
await rig.Ledger.RecordCapitalAsync(okx.AccountId, Strategies.CryptoTrend, 1000m, "EUR", "test", _none).ConfigureAwait(false);
|
||||
await rig.Ledger.RecordCapitalAsync(alpaca.AccountId, Strategies.EquityMomentum, 3000m, "USD", "test", _none).ConfigureAwait(false);
|
||||
|
||||
// A residue below the minimum is written off at market value as a cost: the trade closes (SPEC 7.2).
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, Strategies.CryptoTrend, OrderSide.Buy, 10_000_000m, 0.00001m), _none).ConfigureAwait(false);
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, Strategies.CryptoTrend, OrderSide.Sell, 9_950_000m, 0.000011m), _none).ConfigureAwait(false);
|
||||
await rig.Ledger.WriteOffResidueAsync(okx.AccountId, pepe.Id, Strategies.CryptoTrend, 0.000011m, "below_minimum", _none).ConfigureAwait(false);
|
||||
Assert.IsNull(await rig.Ledger.PositionAsync(okx.AccountId, pepe.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false));
|
||||
var residue = (await rig.QueryAsync("SELECT quantity, value FROM residues", r => (Q: r.Money("quantity"), V: r.Money("value"))).ConfigureAwait(false)).Single();
|
||||
Assert.AreEqual((50_000m, 0.55m), (residue.Q, residue.V));
|
||||
var trade = (await rig.QueryAsync("SELECT status, realized FROM trades WHERE instrument_id = @i", r => (S: r.Text("status"), R: r.Money("realized")), ("i", pepe.Id))
|
||||
.ConfigureAwait(false)).Single();
|
||||
Assert.AreEqual("closed", trade.S);
|
||||
var okxEquity = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == okx.AccountId);
|
||||
Assert.AreEqual(okxEquity.Result, trade.R, "The written-off value is a loss of the trade, nothing else.");
|
||||
|
||||
// A dividend goes to whoever held the stock before the ex-date.
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(alpaca, aapl, Strategies.EquityMomentum, OrderSide.Buy, 10m, 200m), _none).ConfigureAwait(false);
|
||||
rig.Clock.Advance(TimeSpan.FromDays(3));
|
||||
Assert.AreEqual(10m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, rig.Clock.UtcNow, _none).ConfigureAwait(false));
|
||||
Assert.AreEqual(0m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, TradingRig.Start.AddMinutes(-1), _none).ConfigureAwait(false));
|
||||
await rig.Ledger.RecordDividendAsync(alpaca.AccountId, Strategies.EquityMomentum, 2.5m, "USD", rig.Clock.UtcNow, "Dividendo AAPL", _none).ConfigureAwait(false);
|
||||
|
||||
// A 4-for-1 split: four times the shares at a quarter of the price, the value unchanged; applied once.
|
||||
await rig.Ledger.SetStopAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, 180m, _none).ConfigureAwait(false);
|
||||
var before = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId);
|
||||
Assert.IsTrue(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, _none).ConfigureAwait(false));
|
||||
Assert.IsFalse(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, _none).ConfigureAwait(false), "Never twice.");
|
||||
var split = (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!;
|
||||
Assert.AreEqual((40m, 50m, 45m), (split.Quantity, split.AveragePrice, split.StopPrice));
|
||||
Assert.AreEqual(40m, (await rig.Ledger.OpenLotsAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false)).Sum(l => l.Remaining));
|
||||
var after = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId);
|
||||
Assert.AreEqual(before.Equity, after.Equity);
|
||||
Assert.AreEqual(3002.5m, after.Equity, "Capital, plus the dividend; the position at its own price.");
|
||||
|
||||
// A cash row is never changed: it is reversed by an opposite row that points at it.
|
||||
var dividend = (await rig.QueryAsync("SELECT id FROM cash_ledger WHERE kind = 'dividend'", r => r.Id("id")).ConfigureAwait(false)).Single();
|
||||
await rig.Ledger.ReverseCashAsync(dividend, "Dividendo registrato due volte", _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(3000m, (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId).Equity);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task RandomFillsNeverBreakTheBooks()
|
||||
{
|
||||
// Fixed seed (SPEC 18): cash + positions = equity, no negative quantity, lots = position, result = realised + unrealised.
|
||||
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
|
||||
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
|
||||
var eth = await rig.InstrumentAsync(MarketDataStoreTests.Okx("ETH-EUR")).ConfigureAwait(false);
|
||||
const string strategy = Strategies.CryptoTrend;
|
||||
await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 100_000m, "EUR", "test", _none).ConfigureAwait(false);
|
||||
|
||||
var gen = new Gen(Property.DefaultSeed);
|
||||
var prices = new Dictionary<Guid, decimal> { [btc.Id] = 60000m, [eth.Id] = 3000m };
|
||||
for (var step = 0; step < 60; step++)
|
||||
{
|
||||
var instrument = gen.Bool() ? btc : eth;
|
||||
prices[instrument.Id] = Math.Round(prices[instrument.Id] * (1m + gen.Decimal(-0.03m, 0.03m, 4)), 2);
|
||||
var price = prices[instrument.Id];
|
||||
var held = (await rig.Ledger.PositionAsync(account.AccountId, instrument.Id, strategy, _none).ConfigureAwait(false))?.Quantity ?? 0m;
|
||||
var buy = held == 0m || gen.Int(0, 3) > 0;
|
||||
var inKind = gen.Bool();
|
||||
rig.Clock.Advance(TimeSpan.FromMinutes(7));
|
||||
if (buy)
|
||||
{
|
||||
var quantity = gen.Decimal(0.001m, 0.05m, 5);
|
||||
var fee = inKind ? Math.Round(quantity * 0.001m, 8) : Math.Round(quantity * price * 0.002m, 2);
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(account, instrument, strategy, OrderSide.Buy, quantity, price, fee, inKind ? instrument.Spec.BaseCurrency : "EUR"), _none)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
var quantity = gen.Int(0, 4) == 0 ? held : Math.Round(held * gen.Decimal(0.1m, 0.9m, 2), 8);
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(account, instrument, strategy, OrderSide.Sell, quantity, price, Math.Round(quantity * price * 0.002m, 2)), _none)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await rig.Ledger.MarkAsync(instrument.Id, price, _none).ConfigureAwait(false);
|
||||
await AssertBooksAsync(rig, account, strategy, step).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task AssertBooksAsync(TradingRig rig, AccountContext account, string strategy, int step)
|
||||
{
|
||||
var positions = await rig.Ledger.PositionsAsync(account.AccountId, _none).ConfigureAwait(false);
|
||||
var cash = (await rig.QueryAsync("SELECT amount FROM cash_ledger WHERE account_id = @a AND currency = 'EUR'", r => r.Money("amount"), ("a", account.AccountId)).ConfigureAwait(false)).Sum();
|
||||
var equity = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single();
|
||||
Assert.AreEqual(cash + positions.Sum(p => p.Value), equity.Equity, 0.000001m, $"passo {step}: liquidità + posizioni = patrimonio");
|
||||
Assert.IsTrue(positions.All(p => p.Quantity > 0m), $"passo {step}: nessuna quantità negativa");
|
||||
foreach (var position in positions)
|
||||
{
|
||||
var lots = (await rig.Ledger.OpenLotsAsync(account.AccountId, position.InstrumentId, strategy, _none).ConfigureAwait(false)).Sum(l => l.Remaining);
|
||||
Assert.AreEqual(position.Quantity, lots, 0.000000001m, $"passo {step}: lotti = posizione");
|
||||
}
|
||||
|
||||
var realized = (await rig.QueryAsync("SELECT realized FROM trades", r => r.Money("realized")).ConfigureAwait(false)).Sum();
|
||||
Assert.AreEqual(realized + positions.Sum(p => p.Unrealized), equity.Result, 0.0001m, $"passo {step}: risultato = realizzato + non realizzato");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task EquityPhotographsSeparateWorldsAndCorrectForCapitalChanges()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
var fx = new FxStore(rig.Db, rig.Clock);
|
||||
await fx.UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 9), 1.10m, "ecb")], _none).ConfigureAwait(false);
|
||||
var okx = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
|
||||
var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo).ConfigureAwait(false);
|
||||
await rig.Db.WriteAsync(async s =>
|
||||
{
|
||||
foreach (var (strategy, account, share) in new[] { (Strategies.CryptoTrend, okx, 1m), (Strategies.EquityMomentum, alpaca, 0.75m), (Strategies.EquityMeanrev, alpaca, 0.25m) })
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, 'observation', 0, @j, @now, @now, @sh)",
|
||||
_none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", account.AccountId), ("j", new Anubis.Db.DbJson("{}")), ("now", rig.Clock.UtcNow), ("sh", share))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}, _none).ConfigureAwait(false);
|
||||
|
||||
// 4,000 € on OKX all to crypto_trend; 6,000 € on Alpaca at 1.10 $/€ = 6,600 $, 75/25 (SPEC 8.6).
|
||||
var capital = new Capital(rig.Db, rig.Clock, rig.Ledger, fx);
|
||||
await capital.SetAsync(Venues.Okx, 4000m, "test", _none).ConfigureAwait(false);
|
||||
var alpacaCapital = await capital.SetAsync(Venues.Alpaca, 6000m, "test", _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(6600m, alpacaCapital.Amount);
|
||||
var strategies = await capital.StrategiesAsync(Venues.Alpaca, _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(4950m, strategies.Single(s => s.Strategy == Strategies.EquityMomentum).Capital);
|
||||
Assert.AreEqual(1650m, strategies.Single(s => s.Strategy == Strategies.EquityMeanrev).Capital);
|
||||
|
||||
var book = new EquityBook(rig.Db, rig.Clock, rig.Ledger, fx);
|
||||
await book.TakeAsync(_none).ConfigureAwait(false);
|
||||
|
||||
// A gain of 400 € on OKX, then the capital doubles: the return stays 10%, the deposit is no gain.
|
||||
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(okx, btc, Strategies.CryptoTrend, OrderSide.Buy, 0.05m, 60000m), _none).ConfigureAwait(false);
|
||||
await rig.Ledger.MarkAsync(btc.Id, 68000m, _none).ConfigureAwait(false);
|
||||
rig.Clock.Advance(TimeSpan.FromMinutes(5));
|
||||
await book.TakeAsync(_none).ConfigureAwait(false);
|
||||
await capital.SetAsync(Venues.Okx, 8000m, "test", _none).ConfigureAwait(false);
|
||||
rig.Clock.Advance(TimeSpan.FromMinutes(5));
|
||||
await book.TakeAsync(_none).ConfigureAwait(false);
|
||||
|
||||
var series = await rig.QueryAsync("SELECT equity, flows, twr_index, drawdown_pct FROM equity_snapshots WHERE scope = 'strategy' AND strategy = @s ORDER BY taken_at",
|
||||
r => (E: r.Money("equity"), F: r.Money("flows"), I: r.Money("twr_index"), D: r.Money("drawdown_pct")), ("s", Strategies.CryptoTrend)).ConfigureAwait(false);
|
||||
CollectionAssert.AreEqual(new[] { 4000m, 4400m, 8400m }, series.Select(p => p.E).ToArray());
|
||||
Assert.AreEqual(1.1m, series[^1].I);
|
||||
Assert.AreEqual(0.1m, Returns.TimeWeighted(series.Select(p => (p.E, p.F)).ToList()));
|
||||
|
||||
// Simulated money (OKX in the simulator) and demo money are both "simulated": real money is a world apart.
|
||||
var totals = await rig.QueryAsync("SELECT world, currency, equity, fx_effect FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at DESC",
|
||||
r => (W: r.Text("world"), C: r.Text("currency"), E: r.Money("equity"), Fx: r.MoneyOrNull("fx_effect"))).ConfigureAwait(false);
|
||||
Assert.IsTrue(totals.All(t => t.W == Worlds.Simulated && t.C == "EUR"));
|
||||
Assert.AreEqual(8400m + 6000m, totals[0].E, "The total in euro: 6,600 $ at 1.10 is 6,000 €.");
|
||||
Assert.AreEqual(0m, totals[0].Fx, "Same rate as the day of the capital: no FX effect.");
|
||||
|
||||
// Reducing capital below what is invested is refused: the bot never sells to give money back.
|
||||
var error = await Assert.ThrowsExactlyAsync<CapitalException>(() => capital.SetAsync(Venues.Okx, 0m, "test", _none)).ConfigureAwait(false);
|
||||
Assert.Contains("crypto_trend", error.Message);
|
||||
await Assert.ThrowsExactlyAsync<CapitalException>(() =>
|
||||
capital.SetSharesAsync(Venues.Alpaca, new Dictionary<string, decimal> { [Strategies.EquityMomentum] = 0.8m, [Strategies.EquityMeanrev] = 0.3m }, "test", _none)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using Anubis.Brokers;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>Rules without a database: order ids, rounding, the state machine, returns, the live guard (issues #26, #27, #29).</summary>
|
||||
[TestClass]
|
||||
public sealed class TradingRulesTests
|
||||
{
|
||||
internal static InstrumentSpec Stock(string symbol, bool fractionable = true) =>
|
||||
new(Venues.Alpaca, symbol, symbol, AssetClasses.Equity, "USD") { Fractionable = fractionable, TickSize = 0.01m, Status = "active", Exchange = "NASDAQ" };
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ClientOrderIdsAreShortDeterministicAndReadable()
|
||||
{
|
||||
var installation = ClientOrderIds.InstallationCode(Guid.Parse("0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b"));
|
||||
var key = ClientOrderIds.Key(Guid.Parse("0193a1b2-0000-7000-8000-000000000001"));
|
||||
Assert.AreEqual(installation, ClientOrderIds.InstallationCode(Guid.Parse("0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b")));
|
||||
Assert.AreEqual(key, ClientOrderIds.Key(Guid.Parse("0193a1b2-0000-7000-8000-000000000001")));
|
||||
|
||||
var id = ClientOrderIds.Build(installation, TradingEnvironments.Demo, Strategies.EquityMomentum, OrderPurpose.Stop, key, 1297);
|
||||
Assert.AreEqual(ClientOrderIds.Length, id.Length);
|
||||
Assert.IsLessThanOrEqualTo(32, id.Length);
|
||||
Assert.IsTrue(id.StartsWith("ANU", StringComparison.Ordinal));
|
||||
Assert.IsTrue(id.All(char.IsAsciiLetterOrDigit), id);
|
||||
|
||||
// From the id alone: strategy, environment, purpose and progressive (SPEC 7.2, 15.1).
|
||||
var parts = ClientOrderIds.Parse(id);
|
||||
Assert.IsNotNull(parts);
|
||||
Assert.AreEqual(new ClientOrderIdParts(installation, TradingEnvironments.Demo, Strategies.EquityMomentum, OrderPurpose.Stop, key, 1297), parts);
|
||||
Assert.IsTrue(ClientOrderIds.IsOurs(id, installation));
|
||||
Assert.IsFalse(ClientOrderIds.IsOurs(id, "ZZZZ"), "Another installation's order is not ours.");
|
||||
Assert.IsFalse(ClientOrderIds.IsOurs("my-own-order-123", installation), "The user's own orders are never touched.");
|
||||
Assert.IsNull(ClientOrderIds.Parse(null));
|
||||
|
||||
// Every progressive gives a different id; the next one is a different order.
|
||||
Assert.AreNotEqual(id, ClientOrderIds.Build(installation, TradingEnvironments.Demo, Strategies.EquityMomentum, OrderPurpose.Stop, key, 1298));
|
||||
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() =>
|
||||
ClientOrderIds.Build(installation, TradingEnvironments.Demo, Strategies.CryptoTrend, OrderPurpose.Entry, key, ClientOrderIds.MaxSequence + 1));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => ClientOrderIds.Build(installation, TradingEnvironments.Demo, "unknown", OrderPurpose.Entry, key, 1));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void OrdersAreRoundedToTickAndLotAndCheckedAgainstMinimums()
|
||||
{
|
||||
var btc = MarketDataStoreTests.Okx("BTC-EUR") with { MinSize = 0.00001m, TickSize = 0.1m };
|
||||
|
||||
// Quantity down to the lot; a buy limit rounds down and a sell limit up, never past the price asked.
|
||||
var buy = OrderRules.Round(btc, OrderSide.Buy, OrderKind.Limit, 0.0123456789m, 60000m, 60000.17m);
|
||||
Assert.AreEqual(new RoundedOrder(0.01234567m, 60000.1m, null, null), buy);
|
||||
Assert.AreEqual(60000.2m, OrderRules.Round(btc, OrderSide.Sell, OrderKind.Limit, 0.01m, 60000m, 60000.17m).LimitPrice);
|
||||
Assert.AreEqual(OrderReasons.BelowMinimumSize, OrderRules.Round(btc, OrderSide.Buy, OrderKind.Limit, 0.000009m, 60000m, 60000m).Rejection);
|
||||
Assert.AreEqual(OrderReasons.ZeroQuantity, OrderRules.Round(btc, OrderSide.Buy, OrderKind.Limit, 0m, 60000m).Rejection);
|
||||
Assert.AreEqual(OrderReasons.InstrumentClosed, OrderRules.Round(btc with { Status = "suspend" }, OrderSide.Buy, OrderKind.Limit, 1m, 60000m).Rejection);
|
||||
|
||||
// Alpaca: whole shares when not fractionable, nine decimals otherwise, never below 1 $ of value.
|
||||
Assert.AreEqual(3m, OrderRules.Round(Stock("XYZ", fractionable: false), OrderSide.Buy, OrderKind.Limit, 3.9m, 50m, 50m).Quantity);
|
||||
Assert.AreEqual(0.123456789m, OrderRules.Round(Stock("MSFT"), OrderSide.Buy, OrderKind.Limit, 0.1234567891m, 400m, 400m).Quantity);
|
||||
Assert.AreEqual(OrderReasons.BelowMinimumNotional, OrderRules.Round(Stock("MSFT"), OrderSide.Buy, OrderKind.Limit, 0.002m, 400m, 400m).Rejection);
|
||||
|
||||
// A stop protects even a quantity below the minimum value; a stop level rounds up, so it fires a little earlier.
|
||||
var stop = OrderRules.Round(Stock("MSFT"), OrderSide.Sell, OrderKind.Stop, 0.002m, 400m, stopPrice: 380.123m);
|
||||
Assert.IsTrue(stop.IsValid);
|
||||
Assert.AreEqual(380.13m, stop.StopPrice);
|
||||
|
||||
Assert.AreEqual((12m, 0.345m), OrderRules.SplitWhole(12.345m));
|
||||
Assert.IsTrue(OrderRules.IsUnsellable(btc, 0.000005m, 60000m));
|
||||
Assert.IsFalse(OrderRules.IsUnsellable(btc, 0.001m, 60000m));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void OrderStatesOnlyMoveForward()
|
||||
{
|
||||
Assert.IsTrue(OrderStates.CanMove(OrderStatus.Created, OrderStatus.Submitted));
|
||||
Assert.IsTrue(OrderStates.CanMove(OrderStatus.Submitted, OrderStatus.PartiallyFilled));
|
||||
Assert.IsTrue(OrderStates.CanMove(OrderStatus.PartiallyFilled, OrderStatus.PartiallyFilled), "More of the order filled.");
|
||||
Assert.IsTrue(OrderStates.CanMove(OrderStatus.PartiallyFilled, OrderStatus.Filled));
|
||||
Assert.IsTrue(OrderStates.CanMove(OrderStatus.Created, OrderStatus.Filled), "A fill that arrives before the acknowledgement.");
|
||||
Assert.IsFalse(OrderStates.CanMove(OrderStatus.PartiallyFilled, OrderStatus.Submitted));
|
||||
Assert.IsFalse(OrderStates.CanMove(OrderStatus.Submitted, OrderStatus.Created));
|
||||
foreach (var final in new[] { OrderStatus.Filled, OrderStatus.Canceled, OrderStatus.Rejected, OrderStatus.Expired })
|
||||
{
|
||||
Assert.IsTrue(OrderStates.IsFinal(final));
|
||||
foreach (var to in Enum.GetValues<OrderStatus>())
|
||||
{
|
||||
Assert.IsFalse(OrderStates.CanMove(final, to), $"{final} → {to}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TimeWeightedReturnIgnoresDepositsAndWithdrawals()
|
||||
{
|
||||
// 1000 → 1100 (+10%), then 1000 more is given: 2100 → 2310 (+10%). The return is 21%, not 131%.
|
||||
(decimal, decimal)[] points = [(0m, 0m), (1000m, 1000m), (1100m, 1000m), (2100m, 2000m), (2310m, 2000m)];
|
||||
Assert.AreEqual(0.21m, Math.Round(Returns.TimeWeighted(points), 10));
|
||||
|
||||
// A withdrawal is not a loss.
|
||||
(decimal, decimal)[] withdrawal = [(1000m, 1000m), (1000m, 1000m), (500m, 500m)];
|
||||
Assert.AreEqual(0m, Returns.TimeWeighted(withdrawal));
|
||||
|
||||
// 1000 $ given at 1.10 $/€ and still 1000 $: at 1.25 $/€ the euro value fell by the exchange rate alone.
|
||||
var effect = Returns.FxEffect([(1000m, 1.10m)], 1.25m);
|
||||
Assert.AreEqual(Math.Round(1000m / 1.25m - 1000m / 1.10m, 10), Math.Round(effect, 10));
|
||||
Assert.IsLessThan(0m, effect);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void RealAccountsAreRefusedWithoutTheStartupConsent()
|
||||
{
|
||||
Assert.ThrowsExactly<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, TradingConsent.None));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => LiveGuard.Ensure("production", TradingConsent.None));
|
||||
LiveGuard.Ensure(TradingEnvironments.Demo, TradingConsent.None);
|
||||
LiveGuard.Ensure(TradingEnvironments.Simulation, TradingConsent.None);
|
||||
|
||||
// Docker without the variable, or with 0: refused.
|
||||
var env = new Dictionary<string, string?> { ["ANUBIS_DB_ENGINE"] = "sqlite", ["ANUBIS_SECRET_KEY"] = new string('k', 40), ["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1" };
|
||||
var docker = TradingConsent.From(DockerPlatform.Load(env));
|
||||
Assert.IsFalse(docker.AllowLive);
|
||||
Assert.ThrowsExactly<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, docker));
|
||||
env["ANUBIS_ALLOW_LIVE"] = "0";
|
||||
Assert.ThrowsExactly<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, TradingConsent.From(DockerPlatform.Load(env))));
|
||||
|
||||
// Desktop: the config.toml the wizard writes keeps real money off.
|
||||
var root = TempFolder.Create("live");
|
||||
try
|
||||
{
|
||||
var data = new DataDirectory(root);
|
||||
var store = new RestrictedFileStore(Path.Combine(root, "keys"));
|
||||
DesktopPlatform.WriteConfig(data, store, new DbSettings { Engine = DbEngine.Sqlite });
|
||||
var desktop = TradingConsent.From(DesktopPlatform.Load(data, store));
|
||||
Assert.IsFalse(desktop.AllowLive);
|
||||
var refused = Assert.ThrowsExactly<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, desktop));
|
||||
Assert.Contains("config.toml", refused.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(root);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void BrokerAdaptersRefuseARealAccountBeforeAnyRequest()
|
||||
{
|
||||
var http = new FakeHttp();
|
||||
using var client = new HttpClient(http);
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 11, 10, 15, 0, 0, TimeSpan.Zero));
|
||||
Assert.ThrowsExactly<LiveTradingRefusedException>(() =>
|
||||
new AlpacaTrading(client, clock, new AlpacaCredentials("fake-key-id", "fake-secret"), new AlpacaTradingOptions { Environment = TradingEnvironments.Live }, TradingConsent.None));
|
||||
Assert.ThrowsExactly<LiveTradingRefusedException>(() =>
|
||||
new OkxTrading(client, clock, new OkxCredentials("fake-key", "fake-secret", "fake-pass"), new OkxTradingOptions { Environment = TradingEnvironments.Live }, TradingConsent.None));
|
||||
Assert.AreEqual(0, http.Requests.Count, "Nothing may leave before the guard.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// A migrated database on the engine of this run with what trading tests need: a manual clock, quotes set by the
|
||||
/// test, accounts and instruments, the internal simulator and order managers. Tuesday 10 November 2026, 10:00 in New York.
|
||||
/// </summary>
|
||||
internal sealed class TradingRig : IAsyncDisposable
|
||||
{
|
||||
public const string Installation = "TST1";
|
||||
|
||||
public static readonly DateTimeOffset Start = new(2026, 11, 10, 15, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private readonly ConcurrentDictionary<string, Quote> _quotes = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, InstrumentSpec> _specs = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<Guid, Instrument> _instruments = new();
|
||||
private readonly List<IDisposable> _owned = [];
|
||||
|
||||
private TradingRig(TestDb test)
|
||||
{
|
||||
Test = test;
|
||||
Clock = new ManualClock(Start);
|
||||
Ledger = new Ledger(test.Db, Clock);
|
||||
Catalog = new InstrumentCatalog(test.Db, Clock);
|
||||
}
|
||||
|
||||
public TestDb Test { get; }
|
||||
|
||||
public Database Db => Test.Db;
|
||||
|
||||
public ManualClock Clock { get; }
|
||||
|
||||
public Ledger Ledger { get; }
|
||||
|
||||
public InstrumentCatalog Catalog { get; }
|
||||
|
||||
/// <summary>Quotes are refused while this is true: the price feed is "down".</summary>
|
||||
public bool QuotesDown { get; set; }
|
||||
|
||||
public static async Task<TradingRig> CreateAsync() => new(await DatabaseTests.MigratedAsync().ConfigureAwait(false));
|
||||
|
||||
public async Task<AccountContext> AccountAsync(string broker, string environment, string? name = null)
|
||||
{
|
||||
var account = new AccountContext(Ids.NewId(Clock), name ?? AccountSetup.NameOf(broker, environment), broker, environment, Strategies.CurrencyOf(broker));
|
||||
await Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, @n, @b, @e, @c, @now)", CancellationToken.None,
|
||||
("id", account.AccountId), ("n", account.Name), ("b", broker), ("e", environment), ("c", account.Currency), ("now", Clock.UtcNow)), CancellationToken.None).ConfigureAwait(false);
|
||||
return account;
|
||||
}
|
||||
|
||||
public async Task<Instrument> InstrumentAsync(InstrumentSpec spec)
|
||||
{
|
||||
var instrument = await Catalog.EnsureAsync(spec, CancellationToken.None).ConfigureAwait(false);
|
||||
_specs[spec.Symbol] = instrument.Spec;
|
||||
_instruments[instrument.Id] = instrument;
|
||||
return instrument;
|
||||
}
|
||||
|
||||
public static InstrumentSpec Btc => MarketDataStoreTests.Okx("BTC-EUR") with { TickSize = 0.1m, LotSize = 0.00000001m, MinSize = 0.00001m };
|
||||
|
||||
public static InstrumentSpec Pepe => MarketDataStoreTests.Okx("PEPE-EUR") with { TickSize = 0.00000001m, LotSize = 1m, MinSize = 100000m };
|
||||
|
||||
public static InstrumentSpec Stock(string symbol, bool fractionable = true) => TradingRulesTests.Stock(symbol, fractionable);
|
||||
|
||||
public void Quote(string symbol, decimal bid, decimal ask, decimal? size = null) =>
|
||||
_quotes[symbol] = new Quote(symbol, bid, ask, Clock.UtcNow) { BidSize = size, AskSize = size };
|
||||
|
||||
public Task<Quote?> QuoteAsync(string symbol, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(QuotesDown ? null : _quotes.TryGetValue(symbol, out var quote) ? quote : null);
|
||||
|
||||
public Task<Instrument?> FindAsync(Guid id, CancellationToken cancellationToken) => Task.FromResult(_instruments.GetValueOrDefault(id));
|
||||
|
||||
public InstrumentSpec? Spec(string symbol) => _specs.GetValueOrDefault(symbol);
|
||||
|
||||
public PaperBroker Paper(PaperOptions options, Guid accountId, bool persist = true)
|
||||
{
|
||||
var broker = new PaperBroker(options with { MinLatency = TimeSpan.Zero, MaxLatency = TimeSpan.Zero }, Clock, QuoteAsync, Spec,
|
||||
persist ? new PaperBookStore(Db, Clock, accountId) : null);
|
||||
_owned.Add(broker);
|
||||
return broker;
|
||||
}
|
||||
|
||||
public OrderManager Manager(IBrokerAccount broker, AccountContext account, Func<Instrument, CancellationToken, Task<bool>>? marketOpen = null,
|
||||
Func<Instrument, CancellationToken, Task<CorporateAction?>>? pendingSplit = null)
|
||||
{
|
||||
var manager = new OrderManager(Db, Clock, Ledger, broker, account, Installation, FindAsync, QuoteAsync)
|
||||
{
|
||||
ConfirmPrice = QuoteAsync,
|
||||
MarketOpen = marketOpen ?? ((_, _) => Task.FromResult(true)),
|
||||
PendingSplit = pendingSplit,
|
||||
};
|
||||
_owned.Add(manager);
|
||||
return manager;
|
||||
}
|
||||
|
||||
/// <summary>Several turns of the order manager, the clock moving between them (the simulator's latency, the steps).</summary>
|
||||
public async Task TurnsAsync(OrderManager manager, int turns, TimeSpan every)
|
||||
{
|
||||
for (var i = 0; i < turns; i++)
|
||||
{
|
||||
if (manager.Broker is PaperBroker paper)
|
||||
{
|
||||
await paper.PumpAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await manager.TickAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
Clock.Advance(every);
|
||||
}
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<T>> QueryAsync<T>(string sql, Func<DbRow, T> read, params (string, object?)[] args) =>
|
||||
Db.ReadAsync<IReadOnlyList<T>>(async s => await s.QueryAsync(sql, read, args).ConfigureAwait(false), CancellationToken.None);
|
||||
|
||||
public LedgerFill Fill(AccountContext account, Instrument instrument, string strategy, OrderSide side, decimal quantity, decimal price, decimal fee = 0m, string? feeCurrency = null) =>
|
||||
new(account.AccountId, instrument.Id, strategy, "X" + Ids.NewId(Clock).ToString("N"), side, quantity, price, fee, feeCurrency ?? instrument.Spec.QuoteCurrency, Clock.UtcNow);
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
foreach (var owned in _owned)
|
||||
{
|
||||
owned.Dispose();
|
||||
}
|
||||
|
||||
await Test.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user