mirror of
https://github.com/luxfi/dex.git
synced 2026-09-24 00:26:31 +00:00
fix: escape MDX special characters and convert JSX components to markdown
- Escape < characters followed by numbers (e.g., <100ns becomes <100ns) - Convert Tabs/Tab JSX components to markdown headers for compatibility - Convert Cards/Card JSX components to markdown links - Update mdx-components.tsx to include all fumadocs-ui components - These fixes resolve MDX build errors in GitHub Actions
This commit is contained in:
@@ -110,11 +110,11 @@ message PlaceOrderResponse {
|
||||
| Field | Validation |
|
||||
|-------|------------|
|
||||
| `symbol` | Must exist in supported markets |
|
||||
| `price` | > 0, precision <= 8 decimals |
|
||||
| `size` | >= min_order_size, precision <= 8 decimals |
|
||||
| `price` | `> 0`, precision `<= 8` decimals |
|
||||
| `size` | `>= min_order_size`, precision `<= 8` decimals |
|
||||
| `user_id` | Non-empty, valid user |
|
||||
| `client_id` | Max 64 characters, unique per user within 24h |
|
||||
| `stop_price` | > 0 for STOP/STOP_LIMIT orders |
|
||||
| `stop_price` | `> 0` for STOP/STOP_LIMIT orders |
|
||||
|
||||
### Error Codes
|
||||
|
||||
|
||||
@@ -714,7 +714,7 @@ console.log(`Sell pressure: ${(sellRatio * 100).toFixed(1)}%`);
|
||||
```typescript
|
||||
feed.setTradeHandler((trade) => {
|
||||
const threshold = 10; // BTC
|
||||
if (trade.size >= threshold) {
|
||||
if (trade.size >= threshold) {
|
||||
console.log(`LARGE TRADE: ${trade.side.toUpperCase()} ${trade.size} BTC @ ${trade.price}`);
|
||||
// Alert, log, or act on large trade
|
||||
}
|
||||
|
||||
@@ -21,10 +21,10 @@ The LX DEX is a high-performance decentralized exchange built for planet-scale t
|
||||
|
||||
| Metric | Target | Achieved |
|
||||
|--------|--------|----------|
|
||||
| Order Latency | <100ns | 75.9ns |
|
||||
| Order Latency | `<100ns` | 75.9ns |
|
||||
| Throughput | 10M orders/sec | 13M+ orders/sec |
|
||||
| Consensus Finality | <100ms | 50ms |
|
||||
| Memory per Order | <256 bytes | ~200 bytes |
|
||||
| Consensus Finality | `<100ms` | 50ms |
|
||||
| Memory per Order | `<256 bytes` | ~200 bytes |
|
||||
|
||||
## System Architecture
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ Traditional DEX architectures embed trading logic directly in blockchain VMs. Th
|
||||
|----------|---------|------------|-----------|
|
||||
| On-chain VM | 2-30s | 100-1000 TPS | Guaranteed finality, slow |
|
||||
| Hybrid | 100ms-2s | 10K TPS | Compromise |
|
||||
| **Sidecar** | <100us | 10M+ TPS | Fast matching, async settlement |
|
||||
| **Sidecar** | `<100μs` | 10M+ TPS | Fast matching, async settlement |
|
||||
|
||||
The sidecar approach separates concerns:
|
||||
|
||||
@@ -664,7 +664,7 @@ var (
|
||||
|
||||
### ADR-001: Sidecar vs On-Chain Matching
|
||||
|
||||
**Context**: Need to achieve <100us order latency while maintaining settlement guarantees.
|
||||
**Context**: Need to achieve <100us order latency while maintaining settlement guarantees.
|
||||
|
||||
**Decision**: Run matching engine as standalone sidecar, settle via Warp messages.
|
||||
|
||||
|
||||
@@ -119,7 +119,7 @@ type SignerSet struct {
|
||||
Signers []*SignerInfo `json:"signers"` // Active signers (max 100)
|
||||
Waitlist []ids.NodeID `json:"waitlist"` // Validators waiting for slot
|
||||
CurrentEpoch uint64 `json:"currentEpoch"` // Increments ONLY on reshare
|
||||
SetFrozen bool `json:"setFrozen"` // True when signers >= MaxSigners
|
||||
SetFrozen bool `json:"setFrozen"` // True when signers >= MaxSigners
|
||||
ThresholdT int `json:"thresholdT"` // Current t value (T+1 to sign)
|
||||
PublicKey []byte `json:"publicKey"` // Combined threshold public key
|
||||
}
|
||||
@@ -203,7 +203,7 @@ func (vm *VM) RegisterValidator(input *RegisterValidatorInput) (*RegisterValidat
|
||||
vm.signerSet.ThresholdT = int(float64(len(vm.signerSet.Signers)) * vm.config.ThresholdRatio)
|
||||
|
||||
// Check if set should freeze
|
||||
if len(vm.signerSet.Signers) >= vm.config.MaxSigners {
|
||||
if len(vm.signerSet.Signers) >= vm.config.MaxSigners {
|
||||
vm.signerSet.SetFrozen = true
|
||||
}
|
||||
|
||||
@@ -397,10 +397,10 @@ func (vm *VM) BuildBlock(ctx context.Context) (block.Block, error) {
|
||||
// Collect ready bridge requests
|
||||
var requests []*BridgeRequest
|
||||
for _, req := range vm.pendingBridges {
|
||||
if req.Confirmations >= vm.config.MinConfirmations {
|
||||
if req.Confirmations >= vm.config.MinConfirmations {
|
||||
requests = append(requests, req)
|
||||
}
|
||||
if len(requests) >= 100 {
|
||||
if len(requests) >= 100 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,7 +294,7 @@ func (vm *VM) RequestSignature(
|
||||
|
||||
// Check quota
|
||||
vm.checkQuotaReset()
|
||||
if vm.dailySigningCount[requestingChain] >= perms.DailySigningLimit {
|
||||
if vm.dailySigningCount[requestingChain] >= perms.DailySigningLimit {
|
||||
return nil, ErrQuotaExceeded
|
||||
}
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ Latency: 230ms to NY5
|
||||
\ \ | / /
|
||||
Los Angeles ● ●------●-----● ● Amsterdam
|
||||
60ms \ Dallas NYC / 75ms
|
||||
\ 35ms <1ms/
|
||||
\ 35ms <1ms/
|
||||
\ / \
|
||||
\ / \
|
||||
● / \ ● Sao Paulo
|
||||
|
||||
@@ -105,7 +105,7 @@ func (c *ConsensusEngine) CheckFinality(block *Block) bool {
|
||||
|
||||
// Check cumulative stake weight
|
||||
weight := c.CalculateWeight(signatures)
|
||||
return weight >= c.Alpha
|
||||
return weight >= c.Alpha
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@ Flare provides DAG finalization through certificate and skip analysis, determini
|
||||
|
||||
Flare operates on the DAG structure to determine block finality through two mechanisms:
|
||||
|
||||
1. **Certificates**: Block has >= 2f+1 validators supporting it in round r+1
|
||||
2. **Skip Certificates**: Block has >= 2f+1 validators NOT supporting it in round r+1
|
||||
1. **Certificates**: Block has >= 2f+1 validators supporting it in round r+1
|
||||
2. **Skip Certificates**: Block has >= 2f+1 validators NOT supporting it in round r+1
|
||||
|
||||
```
|
||||
+------------------------------------------------------------------+
|
||||
@@ -82,7 +82,7 @@ type Meta interface {
|
||||
// Params holds DAG consensus parameters
|
||||
type Params struct {
|
||||
N int // Total validators
|
||||
F int // Maximum Byzantine validators (N >= 3F + 1)
|
||||
F int // Maximum Byzantine validators (N >= 3F + 1)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -90,7 +90,7 @@ type Params struct {
|
||||
|
||||
### Certificate Detection
|
||||
|
||||
A block has a certificate when >= 2f+1 validators in the next round reference it:
|
||||
A block has a certificate when >= 2f+1 validators in the next round reference it:
|
||||
|
||||
```go
|
||||
// HasCertificate checks if a vertex has achieved certificate status
|
||||
@@ -102,7 +102,7 @@ func HasCertificate(v View, proposer Meta, p Params) bool {
|
||||
for _, m := range next {
|
||||
if v.Supports(m.ID(), proposer.Author(), proposer.Round()) {
|
||||
support++
|
||||
if support >= 2*p.F+1 {
|
||||
if support >= 2*p.F+1 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -113,7 +113,7 @@ func HasCertificate(v View, proposer Meta, p Params) bool {
|
||||
|
||||
### Skip Certificate Detection
|
||||
|
||||
A block should be skipped when >= 2f+1 validators in the next round do NOT reference it:
|
||||
A block should be skipped when >= 2f+1 validators in the next round do NOT reference it:
|
||||
|
||||
```go
|
||||
// HasSkip checks if a vertex should be skipped
|
||||
@@ -125,7 +125,7 @@ func HasSkip(v View, proposer Meta, p Params) bool {
|
||||
for _, m := range next {
|
||||
if !v.Supports(m.ID(), proposer.Author(), proposer.Round()) {
|
||||
nos++
|
||||
if nos >= 2*p.F+1 {
|
||||
if nos >= 2*p.F+1 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -234,7 +234,7 @@ func ChooseFrontier[V VID](frontier []V) []V {
|
||||
}
|
||||
|
||||
// For small frontiers, reference all vertices
|
||||
if len(frontier) <= 3 {
|
||||
if len(frontier) <= 3 {
|
||||
return frontier
|
||||
}
|
||||
|
||||
@@ -242,7 +242,7 @@ func ChooseFrontier[V VID](frontier []V) []V {
|
||||
f := (len(frontier) - 1) / 3
|
||||
required := 2*f + 1
|
||||
|
||||
if required >= len(frontier) {
|
||||
if required >= len(frontier) {
|
||||
return frontier
|
||||
}
|
||||
|
||||
@@ -320,7 +320,7 @@ func LCA[V VID](store Store[V], a, b V) V {
|
||||
```go
|
||||
// Antichain computes mutually unreachable vertices in the DAG
|
||||
func Antichain[V VID](store Store[V], vertices []V) []V {
|
||||
if len(vertices) <= 1 {
|
||||
if len(vertices) <= 1 {
|
||||
return vertices
|
||||
}
|
||||
|
||||
@@ -467,7 +467,7 @@ func (f *Flare) SelectParents(
|
||||
}
|
||||
|
||||
// Select up to maxParents
|
||||
if len(candidates) <= maxParents {
|
||||
if len(candidates) <= maxParents {
|
||||
return candidates
|
||||
}
|
||||
|
||||
@@ -611,10 +611,10 @@ func (f *Flare) FairOrdering(block *Block) []Transaction {
|
||||
|
||||
| Metric | Value | Description |
|
||||
|--------|-------|-------------|
|
||||
| Certificate Time | <0.3ms | Time to achieve 2f+1 support |
|
||||
| Skip Detection | <0.1ms | Time to detect skip condition |
|
||||
| Frontier Update | <0.05ms | Time to update DAG frontier |
|
||||
| Total Finalization | <0.5ms | End-to-end finalization |
|
||||
| Certificate Time | `<0.3ms` | Time to achieve 2f+1 support |
|
||||
| Skip Detection | `<0.1ms` | Time to detect skip condition |
|
||||
| Frontier Update | `<0.05ms` | Time to update DAG frontier |
|
||||
| Total Finalization | `<0.5ms` | End-to-end finalization |
|
||||
|
||||
### Throughput
|
||||
|
||||
@@ -641,7 +641,7 @@ type FinalizeMetrics struct {
|
||||
|
||||
**Property**: If a block receives a certificate, no conflicting block can receive a certificate.
|
||||
|
||||
**Proof**: Certificate requires 2f+1 validators. Two conflicting certificates would require 2*(2f+1) = 4f+2 validators. Since n = 3f+1, this is impossible (4f+2 > 3f+1 for f >= 1).
|
||||
**Proof**: Certificate requires 2f+1 validators. Two conflicting certificates would require 2*(2f+1) = 4f+2 validators. Since n = 3f+1, this is impossible (4f+2 > 3f+1 for f >= 1).
|
||||
|
||||
### Liveness
|
||||
|
||||
|
||||
@@ -214,7 +214,7 @@ func (e *Engine) CheckFinality(block *Block) Decision {
|
||||
| Metric | Target | Achieved |
|
||||
|--------|--------|----------|
|
||||
| Block Time | 1ms | 1ms |
|
||||
| Time to Finality | 1ms | <1ms |
|
||||
| Time to Finality | 1ms | `<1ms` |
|
||||
| Throughput | 100K TPS | 150K TPS |
|
||||
| Concurrent Blocks | 4 | 4 |
|
||||
| Fork Rate | 0% | 0% |
|
||||
@@ -244,7 +244,7 @@ Total ~= 1.0ms
|
||||
The consensus protocol tolerates up to f Byzantine validators where:
|
||||
|
||||
```
|
||||
n >= 3f + 1
|
||||
n >= 3f + 1
|
||||
```
|
||||
|
||||
For the standard 21-validator set:
|
||||
|
||||
@@ -212,10 +212,10 @@ func (p *Photon) ProcessRound(
|
||||
support := p.countSupport(votes, block.ID)
|
||||
|
||||
// Check thresholds
|
||||
if support >= p.params.AlphaConfidence {
|
||||
if support >= p.params.AlphaConfidence {
|
||||
return DecideAccept, nil
|
||||
}
|
||||
if len(votes)-support >= p.params.AlphaConfidence {
|
||||
if len(votes)-support >= p.params.AlphaConfidence {
|
||||
return DecideReject, nil
|
||||
}
|
||||
|
||||
@@ -265,7 +265,7 @@ func (s *ConsensusState) UpdateConfidence(
|
||||
threshold = params.BetaRogue
|
||||
}
|
||||
|
||||
if s.Confidence >= threshold {
|
||||
if s.Confidence >= threshold {
|
||||
if s.Preference {
|
||||
s.FinalDecision = DecideAccept
|
||||
} else {
|
||||
|
||||
@@ -59,46 +59,19 @@ The LX DEX DeFi suite provides institutional-grade financial primitives with pri
|
||||
|
||||
### Core Protocols
|
||||
|
||||
<Cards>
|
||||
<Card title="Lending Protocol" href="./lending">
|
||||
Overcollateralized lending with ZK credit scoring, privacy-preserving positions, and confidential liquidations.
|
||||
</Card>
|
||||
<Card title="Margin Trading" href="./margin">
|
||||
Leveraged perpetual trading up to 50x with cross-margin and isolated margin support.
|
||||
</Card>
|
||||
<Card title="DeFi Vaults" href="./vaults">
|
||||
Automated yield strategies with auto-compounding, delta-neutral positions, and risk-adjusted returns.
|
||||
</Card>
|
||||
<Card title="LUX Staking" href="./staking">
|
||||
Native LUX staking with validator delegation, liquid staking derivatives, and governance participation.
|
||||
</Card>
|
||||
</Cards>
|
||||
|
||||
- [**Lending Protocol**](./lending): Overcollateralized lending with ZK credit scoring, privacy-preserving positions, and confidential liquidations.
|
||||
- [**Margin Trading**](./margin): Leveraged perpetual trading up to 50x with cross-margin and isolated margin support.
|
||||
- [**DeFi Vaults**](./vaults): Automated yield strategies with auto-compounding, delta-neutral positions, and risk-adjusted returns.
|
||||
- [**LUX Staking**](./staking): Native LUX staking with validator delegation, liquid staking derivatives, and governance participation.
|
||||
### Infrastructure
|
||||
|
||||
<Cards>
|
||||
<Card title="AMM & Liquidity" href="./amm">
|
||||
Concentrated liquidity market maker (CLMM) with customizable fee tiers and range orders.
|
||||
</Card>
|
||||
<Card title="Flash Loans" href="./flash">
|
||||
Uncollateralized atomic loans for arbitrage, liquidations, and collateral swaps.
|
||||
</Card>
|
||||
<Card title="Price Oracles" href="./oracles">
|
||||
Multi-source oracle aggregation with TWAP, Chainlink, and Pyth integration.
|
||||
</Card>
|
||||
<Card title="Governance" href="./governance">
|
||||
On-chain governance with timelock, proposal voting, and parameter updates.
|
||||
</Card>
|
||||
</Cards>
|
||||
|
||||
- [**AMM & Liquidity**](./amm): Concentrated liquidity market maker (CLMM) with customizable fee tiers and range orders.
|
||||
- [**Flash Loans**](./flash): Uncollateralized atomic loans for arbitrage, liquidations, and collateral swaps.
|
||||
- [**Price Oracles**](./oracles): Multi-source oracle aggregation with TWAP, Chainlink, and Pyth integration.
|
||||
- [**Governance**](./governance): On-chain governance with timelock, proposal voting, and parameter updates.
|
||||
### Risk Management
|
||||
|
||||
<Cards>
|
||||
<Card title="Risk Parameters" href="./risks">
|
||||
Collateral factors, liquidation thresholds, interest rate models, and protocol limits.
|
||||
</Card>
|
||||
</Cards>
|
||||
|
||||
- [**Risk Parameters**](./risks): Collateral factors, liquidation thresholds, interest rate models, and protocol limits.
|
||||
## Key Features
|
||||
|
||||
### Privacy-Preserving DeFi
|
||||
@@ -168,7 +141,7 @@ The protocol uses a kinked interest rate model for optimal capital efficiency:
|
||||
**Mathematical Formula**:
|
||||
|
||||
```
|
||||
If utilization <= kink:
|
||||
If utilization <= kink:
|
||||
BorrowRate = BaseRate + (Utilization * MultiplierRate)
|
||||
|
||||
If utilization > kink:
|
||||
|
||||
@@ -175,7 +175,7 @@ The protocol uses a kinked interest rate model that increases borrowing costs as
|
||||
```
|
||||
Utilization = TotalBorrows / TotalSupply
|
||||
|
||||
If Utilization <= Kink (80%):
|
||||
If Utilization <= Kink (80%):
|
||||
BorrowRate = BaseRate + Utilization * MultiplierPerYear
|
||||
|
||||
If Utilization > Kink:
|
||||
@@ -231,7 +231,7 @@ contract InterestRateModel {
|
||||
) public view returns (uint256) {
|
||||
uint256 util = utilizationRate(cash, borrows, reserves);
|
||||
|
||||
if (util <= kink) {
|
||||
if (util <= kink) {
|
||||
return baseRatePerBlock + util * multiplierPerBlock / MANTISSA;
|
||||
}
|
||||
|
||||
@@ -410,9 +410,9 @@ func monitorHealthFactor(ctx context.Context, userID string) error {
|
||||
fmt.Printf("Health Factor: %s\n", position.HealthFactor)
|
||||
|
||||
switch {
|
||||
case position.HealthFactor.Cmp(big.NewFloat(1.5)) >= 0:
|
||||
case position.HealthFactor.Cmp(big.NewFloat(1.5)) >= 0:
|
||||
fmt.Println("Status: SAFE")
|
||||
case position.HealthFactor.Cmp(big.NewFloat(1.0)) >= 0:
|
||||
case position.HealthFactor.Cmp(big.NewFloat(1.0)) >= 0:
|
||||
fmt.Println("Status: WARNING - Consider adding collateral")
|
||||
default:
|
||||
fmt.Println("Status: DANGER - Position is liquidatable!")
|
||||
@@ -461,7 +461,7 @@ function maxBorrowable(
|
||||
uint256 debtPrice = oracle.getPrice(borrowAsset);
|
||||
uint256 debtValue = currentDebt * debtPrice / 1e18;
|
||||
|
||||
if (totalCollateralValue <= debtValue) return 0;
|
||||
if (totalCollateralValue <= debtValue) return 0;
|
||||
return (totalCollateralValue - debtValue) * 1e18 / debtPrice;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -99,7 +99,7 @@ func (ob *OrderBook) MatchOrders() []Trade {
|
||||
break
|
||||
}
|
||||
|
||||
// Check if orders cross (bid must be >= ask for a match)
|
||||
// Check if orders cross (bid must be >= ask for a match)
|
||||
if bestBid.Price < bestAsk.Price {
|
||||
break
|
||||
}
|
||||
@@ -149,8 +149,8 @@ func (ob *OrderBook) MatchOrders() []Trade {
|
||||
bestAsk.Filled += tradeSize
|
||||
|
||||
// Check if either order is fully filled
|
||||
bidFullyFilled := bestBid.Filled >= bestBid.Size
|
||||
askFullyFilled := bestAsk.Filled >= bestAsk.Size
|
||||
bidFullyFilled := bestBid.Filled >= bestBid.Size
|
||||
askFullyFilled := bestAsk.Filled >= bestAsk.Size
|
||||
|
||||
if bidFullyFilled {
|
||||
bestBid.Status = Filled
|
||||
@@ -257,14 +257,14 @@ func (ob *OrderBook) tryMatchImmediateLocked(order *Order) uint64 {
|
||||
bestOrder.Filled += tradeSize
|
||||
|
||||
// Handle order status
|
||||
if order.RemainingSize <= 0 {
|
||||
if order.RemainingSize <= 0 {
|
||||
order.Status = Filled
|
||||
} else {
|
||||
order.Status = PartiallyFilled
|
||||
}
|
||||
|
||||
if (bestOrder.RemainingSize <= 0 && bestOrder.Filled >= bestOrder.Size) ||
|
||||
bestOrder.Filled >= bestOrder.Size {
|
||||
if (bestOrder.RemainingSize <= 0 && bestOrder.Filled >= bestOrder.Size) ||
|
||||
bestOrder.Filled >= bestOrder.Size {
|
||||
bestOrder.Status = Filled
|
||||
oppositeTree.removeOrder(bestOrder)
|
||||
delete(ob.Orders, bestOrder.ID)
|
||||
@@ -342,10 +342,10 @@ func (ob *OrderBook) checkSelfTrade(order *Order) bool {
|
||||
}
|
||||
|
||||
if orderUser != "" && orderUser == bestUser {
|
||||
if order.Side == Buy && order.Price >= bestOrder.Price {
|
||||
if order.Side == Buy && order.Price >= bestOrder.Price {
|
||||
return true
|
||||
}
|
||||
if order.Side == Sell && order.Price <= bestOrder.Price {
|
||||
if order.Side == Sell && order.Price <= bestOrder.Price {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -372,10 +372,10 @@ func (ob *OrderBook) wouldTakeLiquidity(order *Order) bool {
|
||||
return false // No liquidity to take
|
||||
}
|
||||
|
||||
if order.Side == Buy && order.Price >= bestOrder.Price {
|
||||
if order.Side == Buy && order.Price >= bestOrder.Price {
|
||||
return true // Would match immediately
|
||||
}
|
||||
if order.Side == Sell && order.Price <= bestOrder.Price {
|
||||
if order.Side == Sell && order.Price <= bestOrder.Price {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -451,7 +451,7 @@ func (book *AdvancedOrderBook) processIcebergOrder(order *AdvancedOrder) ([]Trad
|
||||
|
||||
// refillIceberg refills iceberg order after execution
|
||||
func (book *AdvancedOrderBook) refillIceberg(order *AdvancedOrder, iceberg *IcebergData) {
|
||||
if iceberg.RemainingSize <= 0 {
|
||||
if iceberg.RemainingSize <= 0 {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -493,9 +493,9 @@ func (book *AdvancedOrderBook) processStop(order *AdvancedOrder) ([]Trade, error
|
||||
// shouldTriggerStop checks if stop order should trigger
|
||||
func (book *AdvancedOrderBook) shouldTriggerStop(order *AdvancedOrder) bool {
|
||||
if order.Side == Buy {
|
||||
return book.lastPrice >= order.StopPrice
|
||||
return book.lastPrice >= order.StopPrice
|
||||
}
|
||||
return book.lastPrice <= order.StopPrice
|
||||
return book.lastPrice <= order.StopPrice
|
||||
}
|
||||
|
||||
// triggerStop converts stop order to market/limit
|
||||
@@ -595,9 +595,9 @@ func (book *AdvancedOrderBook) processLimitOrder(order *AdvancedOrder) ([]Trade,
|
||||
|
||||
// Check if order crosses the spread
|
||||
canMatch := false
|
||||
if order.Side == Buy && book.bestAsk > 0 && order.Price >= book.bestAsk {
|
||||
if order.Side == Buy && book.bestAsk > 0 && order.Price >= book.bestAsk {
|
||||
canMatch = true
|
||||
} else if order.Side == Sell && book.bestBid > 0 && order.Price <= book.bestBid {
|
||||
} else if order.Side == Sell && book.bestBid > 0 && order.Price <= book.bestBid {
|
||||
canMatch = true
|
||||
}
|
||||
|
||||
@@ -639,18 +639,18 @@ func (book *AdvancedOrderBook) canFillCompletely(order *AdvancedOrder) bool {
|
||||
|
||||
if order.Side == Buy {
|
||||
for _, o := range *book.askHeap {
|
||||
if order.Type == Market || order.Price >= o.Price {
|
||||
if order.Type == Market || order.Price >= o.Price {
|
||||
availableSize += o.RemainingSize
|
||||
if availableSize >= order.Size {
|
||||
if availableSize >= order.Size {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, o := range *book.bidHeap {
|
||||
if order.Type == Market || order.Price <= o.Price {
|
||||
if order.Type == Market || order.Price <= o.Price {
|
||||
availableSize += o.RemainingSize
|
||||
if availableSize >= order.Size {
|
||||
if availableSize >= order.Size {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -658,7 +658,7 @@ func (tree *OrderTree) getLevels(depth int) []PriceLevel {
|
||||
|
||||
// Build levels
|
||||
for i, price := range prices {
|
||||
if depth > 0 && i >= depth {
|
||||
if depth > 0 && i >= depth {
|
||||
break
|
||||
}
|
||||
priceInt := PriceInt(price * PriceMultiplier)
|
||||
|
||||
@@ -131,7 +131,7 @@ func (tree *OrderTree) getLevels(depth int) []PriceLevel {
|
||||
|
||||
// Build levels
|
||||
for i, price := range prices {
|
||||
if depth > 0 && i >= depth {
|
||||
if depth > 0 && i >= depth {
|
||||
break
|
||||
}
|
||||
priceInt := PriceInt(price * PriceMultiplier)
|
||||
|
||||
@@ -197,7 +197,7 @@ func (p *Position) Update(side OrderSide, size, price float64) {
|
||||
p.RealizedPL += pnl
|
||||
}
|
||||
p.Size -= size
|
||||
if p.Size <= 0 {
|
||||
if p.Size <= 0 {
|
||||
p.Size = 0
|
||||
p.EntryPrice = 0
|
||||
}
|
||||
|
||||
@@ -254,36 +254,15 @@ Session.sendToTarget(order, sessionID);
|
||||
|
||||
## Documentation Sections
|
||||
|
||||
<Cards>
|
||||
<Card title="Quick Start" href="/docs/fix/quickstart">
|
||||
Connect in 15 minutes with step-by-step guide
|
||||
</Card>
|
||||
<Card title="Sessions" href="/docs/fix/sessions">
|
||||
Session management, logon, heartbeat, logout
|
||||
</Card>
|
||||
<Card title="Orders" href="/docs/fix/orders">
|
||||
NewOrderSingle, Cancel, Modify messages
|
||||
</Card>
|
||||
<Card title="Execution Reports" href="/docs/fix/execution">
|
||||
Fills, rejects, and order status updates
|
||||
</Card>
|
||||
<Card title="Market Data" href="/docs/fix/market-data">
|
||||
Subscribe to real-time market data via FIX
|
||||
</Card>
|
||||
<Card title="Drop Copy" href="/docs/fix/drop-copy">
|
||||
Trade capture and reporting
|
||||
</Card>
|
||||
<Card title="Tag Reference" href="/docs/fix/tags">
|
||||
Complete FIX tag documentation
|
||||
</Card>
|
||||
<Card title="Testing" href="/docs/fix/testing">
|
||||
Certification process and testing tools
|
||||
</Card>
|
||||
<Card title="Examples" href="/docs/fix/examples">
|
||||
Sample messages and code examples
|
||||
</Card>
|
||||
</Cards>
|
||||
|
||||
- [**Quick Start**](/docs/fix/quickstart): Connect in 15 minutes with step-by-step guide
|
||||
- [**Sessions**](/docs/fix/sessions): Session management, logon, heartbeat, logout
|
||||
- [**Orders**](/docs/fix/orders): NewOrderSingle, Cancel, Modify messages
|
||||
- [**Execution Reports**](/docs/fix/execution): Fills, rejects, and order status updates
|
||||
- [**Market Data**](/docs/fix/market-data): Subscribe to real-time market data via FIX
|
||||
- [**Drop Copy**](/docs/fix/drop-copy): Trade capture and reporting
|
||||
- [**Tag Reference**](/docs/fix/tags): Complete FIX tag documentation
|
||||
- [**Testing**](/docs/fix/testing): Certification process and testing tools
|
||||
- [**Examples**](/docs/fix/examples): Sample messages and code examples
|
||||
## Support
|
||||
|
||||
| Channel | Contact |
|
||||
|
||||
@@ -502,7 +502,7 @@ func (m *ConnectionMonitor) Start() {
|
||||
if err != nil || latency > 1*time.Millisecond {
|
||||
missedHeartbeats++
|
||||
|
||||
if missedHeartbeats >= m.failoverThreshold {
|
||||
if missedHeartbeats >= m.failoverThreshold {
|
||||
// Failover to backup
|
||||
m.active.Store(m.backup)
|
||||
log.Warn("Failover to backup connection")
|
||||
|
||||
@@ -16,7 +16,7 @@ LX DEX delivers **institutional-grade HFT infrastructure** with the lowest laten
|
||||
| **Finality** | **1ms** | ~400ms | ~1s | Instant |
|
||||
| **Colocation** | **Yes** | No | No | Yes |
|
||||
| **Binary Protocol** | **Yes** | No | No | Yes |
|
||||
| **Kill Switch** | **<1us** | N/A | N/A | ~1ms |
|
||||
| **Kill Switch** | **<1us** | N/A | N/A | ~1ms |
|
||||
|
||||
### Key Advantages
|
||||
|
||||
@@ -246,27 +246,12 @@ md.on_trade([](const Trade& trade) {
|
||||
|
||||
## Next Steps
|
||||
|
||||
<Cards>
|
||||
<Card title="Colocation" href="/docs/hft/colocation">
|
||||
Data center options and network topology
|
||||
</Card>
|
||||
<Card title="Connectivity" href="/docs/hft/connectivity">
|
||||
Direct connections and dedicated lines
|
||||
</Card>
|
||||
<Card title="Protocols" href="/docs/hft/protocols">
|
||||
Binary protocol specification
|
||||
</Card>
|
||||
<Card title="Latency" href="/docs/hft/latency">
|
||||
Detailed latency benchmarks
|
||||
</Card>
|
||||
<Card title="Market Data" href="/docs/hft/marketdata">
|
||||
Low-latency market data feeds
|
||||
</Card>
|
||||
<Card title="Onboarding" href="/docs/hft/onboarding">
|
||||
HFT application process
|
||||
</Card>
|
||||
</Cards>
|
||||
|
||||
- [**Colocation**](/docs/hft/colocation): Data center options and network topology
|
||||
- [**Connectivity**](/docs/hft/connectivity): Direct connections and dedicated lines
|
||||
- [**Protocols**](/docs/hft/protocols): Binary protocol specification
|
||||
- [**Latency**](/docs/hft/latency): Detailed latency benchmarks
|
||||
- [**Market Data**](/docs/hft/marketdata): Low-latency market data feeds
|
||||
- [**Onboarding**](/docs/hft/onboarding): HFT application process
|
||||
## Contact
|
||||
|
||||
**Institutional Trading Desk**
|
||||
|
||||
@@ -24,46 +24,19 @@ LX DEX Institutional combines the transparency and self-custody benefits of dece
|
||||
|
||||
### Trading Infrastructure
|
||||
|
||||
<Cards>
|
||||
<Card title="Prime Brokerage" href="/docs/institutional/prime">
|
||||
Credit facilities, margin financing, and cross-margining across asset classes
|
||||
</Card>
|
||||
<Card title="OTC Desk" href="/docs/institutional/otc">
|
||||
Block trades, RFQ system, and bespoke execution for large orders
|
||||
</Card>
|
||||
<Card title="Enterprise API" href="/docs/institutional/api-enterprise">
|
||||
Dedicated endpoints, co-location, and custom integrations
|
||||
</Card>
|
||||
</Cards>
|
||||
|
||||
- [**Prime Brokerage**](/docs/institutional/prime): Credit facilities, margin financing, and cross-margining across asset classes
|
||||
- [**OTC Desk**](/docs/institutional/otc): Block trades, RFQ system, and bespoke execution for large orders
|
||||
- [**Enterprise API**](/docs/institutional/api-enterprise): Dedicated endpoints, co-location, and custom integrations
|
||||
### Operations & Custody
|
||||
|
||||
<Cards>
|
||||
<Card title="Custody Solutions" href="/docs/institutional/custody">
|
||||
MPC wallets, cold storage, and institutional-grade key management
|
||||
</Card>
|
||||
<Card title="Settlement" href="/docs/institutional/settlement">
|
||||
T+0 atomic settlement, DVP, and cross-chain delivery
|
||||
</Card>
|
||||
<Card title="Compliance" href="/docs/institutional/compliance">
|
||||
Transaction monitoring, sanctions screening, and regulatory reporting
|
||||
</Card>
|
||||
</Cards>
|
||||
|
||||
- [**Custody Solutions**](/docs/institutional/custody): MPC wallets, cold storage, and institutional-grade key management
|
||||
- [**Settlement**](/docs/institutional/settlement): T+0 atomic settlement, DVP, and cross-chain delivery
|
||||
- [**Compliance**](/docs/institutional/compliance): Transaction monitoring, sanctions screening, and regulatory reporting
|
||||
### Governance & Reporting
|
||||
|
||||
<Cards>
|
||||
<Card title="Reporting" href="/docs/institutional/reporting">
|
||||
Trade confirmations, tax reports, and audit trails
|
||||
</Card>
|
||||
<Card title="SLA" href="/docs/institutional/sla">
|
||||
99.99% uptime guarantee with financial penalties
|
||||
</Card>
|
||||
<Card title="Onboarding" href="/docs/institutional/onboarding">
|
||||
KYB verification, documentation, and dedicated support
|
||||
</Card>
|
||||
</Cards>
|
||||
|
||||
- [**Reporting**](/docs/institutional/reporting): Trade confirmations, tax reports, and audit trails
|
||||
- [**SLA**](/docs/institutional/sla): 99.99% uptime guarantee with financial penalties
|
||||
- [**Onboarding**](/docs/institutional/onboarding): KYB verification, documentation, and dedicated support
|
||||
## Client Segments
|
||||
|
||||
### Hedge Funds
|
||||
@@ -234,14 +207,6 @@ See [Onboarding Guide](/docs/institutional/onboarding) for detailed requirements
|
||||
|
||||
## Documentation
|
||||
|
||||
<Cards>
|
||||
<Card title="API Documentation" href="/docs/api">
|
||||
Complete API reference with examples
|
||||
</Card>
|
||||
<Card title="SDK Libraries" href="/docs/sdk">
|
||||
Client libraries for all major languages
|
||||
</Card>
|
||||
<Card title="FIX Protocol" href="/docs/institutional/api-enterprise#fix-protocol">
|
||||
FIX 4.4 and 5.0 connectivity
|
||||
</Card>
|
||||
</Cards>
|
||||
- [**API Documentation**](/docs/api): Complete API reference with examples
|
||||
- [**SDK Libraries**](/docs/sdk): Client libraries for all major languages
|
||||
- [**FIX Protocol**](/docs/institutional/api-enterprise#fix-protocol): FIX 4.4 and 5.0 connectivity
|
||||
|
||||
@@ -42,25 +42,25 @@ LX DEX provides market makers with dedicated API infrastructure designed for hig
|
||||
|
||||
| Protocol | Endpoint | Port | Latency |
|
||||
|----------|----------|------|---------|
|
||||
| REST | `https://mm-api.lux.network` | 443 | <10ms |
|
||||
| WebSocket | `wss://mm-ws.lux.network` | 443 | <5ms |
|
||||
| gRPC | `mm-grpc.lux.network` | 9090 | <1ms |
|
||||
| REST | `https://mm-api.lux.network` | 443 | <10ms |
|
||||
| WebSocket | `wss://mm-ws.lux.network` | 443 | <5ms |
|
||||
| gRPC | `mm-grpc.lux.network` | 9090 | <1ms |
|
||||
|
||||
### Priority Endpoints (Tier 3+)
|
||||
|
||||
| Protocol | Endpoint | Port | Latency |
|
||||
|----------|----------|------|---------|
|
||||
| REST | `https://priority.lux.network` | 443 | <1ms |
|
||||
| WebSocket | `wss://priority-ws.lux.network` | 443 | <500us |
|
||||
| gRPC | `priority-grpc.lux.network` | 9090 | <100us |
|
||||
| FIX | `fix.lux.network` | 4433 | <100us |
|
||||
| REST | `https://priority.lux.network` | 443 | <1ms |
|
||||
| WebSocket | `wss://priority-ws.lux.network` | 443 | <500us |
|
||||
| gRPC | `priority-grpc.lux.network` | 9090 | <100us |
|
||||
| FIX | `fix.lux.network` | 4433 | <100us |
|
||||
|
||||
### Co-location Endpoints (Tier 4)
|
||||
|
||||
| Protocol | Endpoint | Port | Latency |
|
||||
|----------|----------|------|---------|
|
||||
| Direct | `10.0.1.x` (assigned) | Various | <10us |
|
||||
| FIX | `10.0.2.x` (assigned) | 4433 | <10us |
|
||||
| Direct | `10.0.1.x` (assigned) | Various | <10us |
|
||||
| FIX | `10.0.2.x` (assigned) | 4433 | <10us |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -127,15 +127,15 @@ def calculate_monthly_rebate(maker_volume: float, tier: int) -> dict:
|
||||
base_rebate = maker_volume * base_rates[tier]
|
||||
|
||||
# Volume bonus tiers
|
||||
if maker_volume >= 10_000_000_000: # $10B+
|
||||
if maker_volume >= 10_000_000_000: # $10B+
|
||||
bonus_rate = 0.00025 # 2.5 bps
|
||||
elif maker_volume >= 5_000_000_000: # $5B+
|
||||
elif maker_volume >= 5_000_000_000: # $5B+
|
||||
bonus_rate = 0.00020 # 2.0 bps
|
||||
elif maker_volume >= 1_000_000_000: # $1B+
|
||||
elif maker_volume >= 1_000_000_000: # $1B+
|
||||
bonus_rate = 0.00015 # 1.5 bps
|
||||
elif maker_volume >= 500_000_000: # $500M+
|
||||
elif maker_volume >= 500_000_000: # $500M+
|
||||
bonus_rate = 0.00010 # 1.0 bps
|
||||
elif maker_volume >= 100_000_000: # $100M+
|
||||
elif maker_volume >= 100_000_000: # $100M+
|
||||
bonus_rate = 0.00005 # 0.5 bps
|
||||
else:
|
||||
bonus_rate = 0
|
||||
@@ -176,7 +176,7 @@ For MMs providing liquidity in newly listed markets:
|
||||
|---------|----------|---------|
|
||||
| Launch Bonus | First 30 days | +50% maker rebate |
|
||||
| Depth Bonus | First 30 days | +$0.50/$1K depth/hour |
|
||||
| Spread Bonus | First 30 days | +$1K/day for <3 bps spread |
|
||||
| Spread Bonus | First 30 days | +$1K/day for <3 bps spread |
|
||||
|
||||
### Liquidity Mining Rewards
|
||||
|
||||
|
||||
@@ -292,9 +292,9 @@ tier_score = (
|
||||
)
|
||||
|
||||
# Tier Assignment
|
||||
if tier_score >= 95: tier = 4
|
||||
elif tier_score >= 85: tier = 3
|
||||
elif tier_score >= 70: tier = 2
|
||||
if tier_score >= 95: tier = 4
|
||||
elif tier_score >= 85: tier = 3
|
||||
elif tier_score >= 70: tier = 2
|
||||
else: tier = 1
|
||||
```
|
||||
|
||||
|
||||
@@ -303,8 +303,8 @@ Market makers have access to real-time performance metrics:
|
||||
│ └─────────────┘ └─────────────┘ └─────────────┘ │
|
||||
│ │
|
||||
│ Markets Quoted: 35/30 required │
|
||||
│ RFQ Response: 45ms avg (Target: <50ms) │
|
||||
│ Quote Updates: 85ms avg (Target: <100ms) │
|
||||
│ RFQ Response: 45ms avg (Target: <50ms) │
|
||||
│ Quote Updates: 85ms avg (Target: <100ms) │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
@@ -314,7 +314,7 @@ Market makers have access to real-time performance metrics:
|
||||
| Alert Type | Trigger | Notification |
|
||||
|------------|---------|--------------|
|
||||
| Spread Violation | >150% of max spread | Immediate |
|
||||
| Depth Below Min | <80% of required | Immediate |
|
||||
| Depth Below Min | <80% of required | Immediate |
|
||||
| Uptime Warning | 3% below target | Every 15 mins |
|
||||
| Stale Quotes | >2x max age | Immediate |
|
||||
| RFQ Timeout | >2x max response | Immediate |
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"pages": [
|
||||
"index",
|
||||
"getting-started",
|
||||
"---Core Platform---",
|
||||
"---Core Concepts---",
|
||||
"architecture",
|
||||
"engine",
|
||||
"orderbook",
|
||||
@@ -13,12 +13,6 @@
|
||||
"trading",
|
||||
"hft",
|
||||
"market-makers",
|
||||
"---API Reference---",
|
||||
"api",
|
||||
"...api",
|
||||
"---SDK Guide---",
|
||||
"sdk",
|
||||
"...sdk",
|
||||
"---DeFi & Bridge---",
|
||||
"defi",
|
||||
"lending",
|
||||
@@ -41,10 +35,16 @@
|
||||
"---Learn---",
|
||||
"tutorials",
|
||||
"examples",
|
||||
"---Reference---",
|
||||
"---Development---",
|
||||
"development",
|
||||
"specifications",
|
||||
"source",
|
||||
"reference",
|
||||
"development"
|
||||
"---API Reference---",
|
||||
"api",
|
||||
"...api",
|
||||
"---SDK Guide---",
|
||||
"sdk",
|
||||
"...sdk"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -11,13 +11,13 @@ LX DEX is engineered for **High-Frequency Trading (HFT)** performance, achieving
|
||||
|
||||
| Metric | Target | Achieved | Notes |
|
||||
|--------|--------|----------|-------|
|
||||
| Order Latency (GPU) | <1 us | **2 ns** | 500x better than target |
|
||||
| Order Latency (CPU) | <1 us | **487 ns** | Lock-free data structures |
|
||||
| Order Latency (GPU) | <1 us | **2 ns** | 500x better than target |
|
||||
| Order Latency (CPU) | <1 us | **487 ns** | Lock-free data structures |
|
||||
| Throughput (CPU) | 1M/sec | **1.01M/sec** | Pure Go, no CGO |
|
||||
| Throughput (GPU) | 100M/sec | **434M/sec** | MLX on Apple Silicon |
|
||||
| Memory per 100K orders | <1 GB | **847 MB** | Object pooling |
|
||||
| P99 Latency | <10 us | **2.3 us** | Tail latency controlled |
|
||||
| GC Pause | <1 ms | **0.3 ms** | GOGC tuning |
|
||||
| Memory per 100K orders | <1 GB | **847 MB** | Object pooling |
|
||||
| P99 Latency | <10 us | **2.3 us** | Tail latency controlled |
|
||||
| GC Pause | <1 ms | **0.3 ms** | GOGC tuning |
|
||||
|
||||
## Comparison with Major Exchanges
|
||||
|
||||
@@ -192,7 +192,7 @@ export GOMEMLIMIT=8GiB # Hard memory limit
|
||||
export GOMAXPROCS=8 # Match physical cores
|
||||
|
||||
# Enable memory ballast (reduces GC frequency)
|
||||
# In code: var ballast = make([]byte, 10<<30) // 10GB ballast
|
||||
# In code: var ballast = make([]byte, 10<<30) // 10GB ballast
|
||||
```
|
||||
|
||||
### Hardware Requirements
|
||||
@@ -241,9 +241,9 @@ type Metrics struct {
|
||||
|
||||
| Metric | Target | Alert Threshold |
|
||||
|--------|--------|-----------------|
|
||||
| Order Latency P99 | <10 us | >50 us |
|
||||
| Match Latency P99 | <1 us | >5 us |
|
||||
| GC Pause P99 | <1 ms | >5 ms |
|
||||
| Throughput | >1M/sec | <500K/sec |
|
||||
| Error Rate | <0.001% | >0.01% |
|
||||
| Network RTT | <100 us | >1 ms |
|
||||
| Order Latency P99 | <10 us | >50 us |
|
||||
| Match Latency P99 | <1 us | >5 us |
|
||||
| GC Pause P99 | <1 ms | >5 ms |
|
||||
| Throughput | >1M/sec | <500K/sec |
|
||||
| Error Rate | <0.001% | >0.01% |
|
||||
| Network RTT | <100 us | >1 ms |
|
||||
|
||||
@@ -259,7 +259,7 @@ func init() {
|
||||
// FindPrice uses binary search within cache lines
|
||||
func (t *CacheAlignedTree) FindPrice(price int64) (int64, bool) {
|
||||
idx := t.root
|
||||
for idx >= 0 {
|
||||
for idx >= 0 {
|
||||
node := &t.nodes[idx]
|
||||
|
||||
// Binary search within node (cache-hot)
|
||||
@@ -291,12 +291,12 @@ package orderbook
|
||||
func (ob *OrderBook) ProcessOrderBranchy(order *Order) {
|
||||
if order.Side == Buy {
|
||||
ob.bids.Insert(order)
|
||||
if order.Price >= ob.bestAsk {
|
||||
if order.Price >= ob.bestAsk {
|
||||
ob.matchBuy(order)
|
||||
}
|
||||
} else {
|
||||
ob.asks.Insert(order)
|
||||
if order.Price <= ob.bestBid {
|
||||
if order.Price <= ob.bestBid {
|
||||
ob.matchSell(order)
|
||||
}
|
||||
}
|
||||
@@ -313,8 +313,8 @@ func NewOrderBook() *OrderBook {
|
||||
return &OrderBook{
|
||||
books: [2]*PriceLevels{NewPriceLevels(), NewPriceLevels()},
|
||||
compareFns: [2]func(int64, int64) bool{
|
||||
func(a, b int64) bool { return a >= b }, // Buy: price >= ask
|
||||
func(a, b int64) bool { return a <= b }, // Sell: price <= bid
|
||||
func(a, b int64) bool { return a >= b }, // Buy: price >= ask
|
||||
func(a, b int64) bool { return a <= b }, // Sell: price <= bid
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ func (p *OrderPool) Release(order *Order) {
|
||||
// Find index
|
||||
idx := int((uintptr(unsafe.Pointer(order)) - uintptr(unsafe.Pointer(&p.orders[0]))) / unsafe.Sizeof(Order{}))
|
||||
|
||||
if idx >= 0 && idx < OrderPoolSize && p.inUse[idx] {
|
||||
if idx >= 0 && idx < OrderPoolSize && p.inUse[idx] {
|
||||
p.inUse[idx] = false
|
||||
select {
|
||||
case p.free <- idx:
|
||||
@@ -415,7 +415,7 @@ var ballast []byte
|
||||
|
||||
func init() {
|
||||
// 10GB ballast - GC runs when heap doubles from this baseline
|
||||
ballast = make([]byte, 10<<30)
|
||||
ballast = make([]byte, 10<<30)
|
||||
|
||||
// Set GOGC and GOMEMLIMIT
|
||||
debug.SetGCPercent(400) // GC at 400% of baseline (less frequent)
|
||||
|
||||
@@ -319,7 +319,7 @@ loop:
|
||||
// Load 4 prices into YMM1
|
||||
VMOVDQU (SI)(BX*8), Y1
|
||||
|
||||
// Compare: Y2 = (Y0 >= Y1)
|
||||
// Compare: Y2 = (Y0 >= Y1)
|
||||
VPCMPGTQ Y1, Y0, Y2
|
||||
VPCMPEQQ Y1, Y0, Y3
|
||||
VPOR Y2, Y3, Y2
|
||||
@@ -343,7 +343,7 @@ done:
|
||||
func MatchPricesFallback(orderPrice int64, prices []int64) uint64 {
|
||||
var result uint64
|
||||
for i, price := range prices {
|
||||
if orderPrice >= price {
|
||||
if orderPrice >= price {
|
||||
result |= 1 << i
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,8 +44,8 @@ Pre-trade risk checks validate every order before it enters the matching engine,
|
||||
v
|
||||
┌─────────────────────────────────────────────────────────────────────────┐
|
||||
│ 4. SIZE VALIDATION Latency: ~100ns │
|
||||
│ • Size >= minimum order size │
|
||||
│ • Size <= maximum order size │
|
||||
│ • Size >= minimum order size │
|
||||
│ • Size <= maximum order size │
|
||||
│ • Size within lot size (size % lot_size == 0) │
|
||||
│ • Notional value within limits │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
@@ -54,7 +54,7 @@ Pre-trade risk checks validate every order before it enters the matching engine,
|
||||
┌─────────────────────────────────────────────────────────────────────────┐
|
||||
│ 5. BALANCE/MARGIN CHECK Latency: ~500ns │
|
||||
│ • Calculate required margin for order │
|
||||
│ • Check available balance >= required │
|
||||
│ • Check available balance >= required │
|
||||
│ • Reserve margin for order │
|
||||
│ • Update buying power │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
@@ -492,7 +492,7 @@ func (rl *RateLimiter) CheckOrderRate(userID string) error {
|
||||
}
|
||||
|
||||
// Check open order count
|
||||
if int(rl.openOrders.Load()) >= rl.limits.MaxOpenOrders {
|
||||
if int(rl.openOrders.Load()) >= rl.limits.MaxOpenOrders {
|
||||
return fmt.Errorf("%w: %d max open orders",
|
||||
ErrMaxOpenOrdersExceeded, rl.limits.MaxOpenOrders)
|
||||
}
|
||||
|
||||
@@ -475,7 +475,7 @@ static int find_level(struct lxdex_level *levels, size_t count,
|
||||
|
||||
static void insert_level(struct lxdex_level *levels, size_t *count,
|
||||
int pos, const struct lxdex_level *level) {
|
||||
if (*count >= MAX_LEVELS) return;
|
||||
if (*count >= MAX_LEVELS) return;
|
||||
|
||||
// Shift levels down
|
||||
memmove(&levels[pos + 1], &levels[pos],
|
||||
@@ -486,7 +486,7 @@ static void insert_level(struct lxdex_level *levels, size_t *count,
|
||||
}
|
||||
|
||||
static void remove_level(struct lxdex_level *levels, size_t *count, int pos) {
|
||||
if (pos >= (int)*count) return;
|
||||
if (pos >= (int)*count) return;
|
||||
|
||||
memmove(&levels[pos], &levels[pos + 1],
|
||||
(*count - pos - 1) * sizeof(struct lxdex_level));
|
||||
@@ -496,7 +496,7 @@ static void remove_level(struct lxdex_level *levels, size_t *count, int pos) {
|
||||
void local_book_apply_delta(struct local_orderbook *book,
|
||||
const struct lxdex_orderbook_delta *delta) {
|
||||
// Skip old updates
|
||||
if (delta->sequence <= book->sequence) {
|
||||
if (delta->sequence <= book->sequence) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -527,13 +527,13 @@ void local_book_apply_delta(struct local_orderbook *book,
|
||||
break;
|
||||
|
||||
case LXDEX_DELTA_UPDATE:
|
||||
if (idx >= 0) {
|
||||
if (idx >= 0) {
|
||||
levels[idx].size = delta->size;
|
||||
}
|
||||
break;
|
||||
|
||||
case LXDEX_DELTA_DELETE:
|
||||
if (idx >= 0) {
|
||||
if (idx >= 0) {
|
||||
remove_level(levels, count, idx);
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -108,7 +108,7 @@ struct PriceLevel {
|
||||
};
|
||||
|
||||
// Cache-line aligned for performance
|
||||
static_assert(sizeof(PriceLevel) <= 64);
|
||||
static_assert(sizeof(PriceLevel) <= 64);
|
||||
static_assert(alignof(PriceLevel) == 64);
|
||||
|
||||
} // namespace lxdex
|
||||
@@ -407,7 +407,7 @@ for (const auto& [price_bucket, total_qty] : aggregated.bids()) {
|
||||
```cpp
|
||||
// Filter by minimum quantity
|
||||
auto large_orders = book.filter([](const PriceLevel& level) {
|
||||
return level.quantity >= Quantity::from_string("10.0");
|
||||
return level.quantity >= Quantity::from_string("10.0");
|
||||
});
|
||||
|
||||
// Filter by price range
|
||||
|
||||
@@ -102,7 +102,7 @@ Price spread = ask - bid;
|
||||
Quantity total = quantity * Price{2};
|
||||
|
||||
// Comparison
|
||||
if (bid >= Price{49000'00000000}) {
|
||||
if (bid >= Price{49000'00000000}) {
|
||||
// ...
|
||||
}
|
||||
|
||||
@@ -542,7 +542,7 @@ client.place_order(order);
|
||||
| `QuantityRange` | Quantity within min/max for symbol |
|
||||
| `TickSize` | Price must be multiple of tick size |
|
||||
| `LotSize` | Quantity must be multiple of lot size |
|
||||
| `NotionalValue` | Order value >= minimum notional |
|
||||
| `NotionalValue` | Order value >= minimum notional |
|
||||
|
||||
## Performance Tips
|
||||
|
||||
|
||||
@@ -595,10 +595,10 @@ func (mm *MarginMonitor) checkMargin(ctx context.Context) {
|
||||
|
||||
ratio := marginInfo.MarginRatio
|
||||
|
||||
if ratio >= mm.criticalLevel {
|
||||
if ratio >= mm.criticalLevel {
|
||||
fmt.Printf("[CRITICAL] Margin ratio: %.1f%% - LIQUIDATION IMMINENT!\n", ratio*100)
|
||||
// Could trigger automatic position reduction here
|
||||
} else if ratio >= mm.warningLevel {
|
||||
} else if ratio >= mm.warningLevel {
|
||||
fmt.Printf("[WARNING] Margin ratio: %.1f%% - Consider reducing exposure\n", ratio*100)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -547,7 +547,7 @@ func MarketImpact(ob *client.OrderBook, side client.OrderSide, size float64) (av
|
||||
var totalCost float64
|
||||
|
||||
for _, level := range levels {
|
||||
if remaining <= 0 {
|
||||
if remaining <= 0 {
|
||||
break
|
||||
}
|
||||
|
||||
@@ -662,13 +662,13 @@ func OrderBookImbalance(ob *client.OrderBook, pctRange float64) float64 {
|
||||
var bidVolume, askVolume float64
|
||||
|
||||
for _, bid := range ob.Bids {
|
||||
if bid.Price >= lowerBound {
|
||||
if bid.Price >= lowerBound {
|
||||
bidVolume += bid.Size
|
||||
}
|
||||
}
|
||||
|
||||
for _, ask := range ob.Asks {
|
||||
if ask.Price <= upperBound {
|
||||
if ask.Price <= upperBound {
|
||||
askVolume += ask.Size
|
||||
}
|
||||
}
|
||||
|
||||
@@ -494,7 +494,7 @@ func main() {
|
||||
orders := make([]*client.Order, 0, 20)
|
||||
|
||||
// Buy orders below market
|
||||
for i := 1; i <= 10; i++ {
|
||||
for i := 1; i <= 10; i++ {
|
||||
orders = append(orders, &client.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: client.OrderTypeLimit,
|
||||
@@ -508,7 +508,7 @@ func main() {
|
||||
}
|
||||
|
||||
// Sell orders above market
|
||||
for i := 1; i <= 10; i++ {
|
||||
for i := 1; i <= 10; i++ {
|
||||
orders = append(orders, &client.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: client.OrderTypeLimit,
|
||||
@@ -610,7 +610,7 @@ func main() {
|
||||
|
||||
// Place buy order at best bid - $10 (deeper in book)
|
||||
buyPrice := orderBook.BestBid() - 10
|
||||
if buyPrice <= 0 {
|
||||
if buyPrice <= 0 {
|
||||
log.Fatal("Invalid buy price")
|
||||
}
|
||||
|
||||
@@ -716,11 +716,11 @@ func placeOrderWithRetry(c *client.Client, order *client.Order, maxRetries int)
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
return len(s) >= len(substr) && (s == substr || len(s) > 0 && containsImpl(s, substr))
|
||||
return len(s) >= len(substr) && (s == substr || len(s) > 0 && containsImpl(s, substr))
|
||||
}
|
||||
|
||||
func containsImpl(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -303,7 +303,7 @@ func (ta *TradeAggregator) GetRecentTrades(symbol string, limit int) []*client.T
|
||||
defer ta.mu.RUnlock()
|
||||
|
||||
trades := ta.trades[symbol]
|
||||
if len(trades) <= limit {
|
||||
if len(trades) <= limit {
|
||||
result := make([]*client.Trade, len(trades))
|
||||
copy(result, trades)
|
||||
return result
|
||||
@@ -442,7 +442,7 @@ func BuildVolumeProfile(trades []*client.Trade, buckets int) []PriceVolume {
|
||||
volumeMap := make(map[int]float64)
|
||||
for _, trade := range trades {
|
||||
bucket := int((trade.Price - minPrice) / bucketSize)
|
||||
if bucket >= buckets {
|
||||
if bucket >= buckets {
|
||||
bucket = buckets - 1
|
||||
}
|
||||
volumeMap[bucket] += trade.Size
|
||||
@@ -551,7 +551,7 @@ func AnalyzeTradeFlow(trades []*client.Trade, largeThreshold float64) *TradeFlow
|
||||
flow.SellCount++
|
||||
}
|
||||
|
||||
if trade.Size >= largeThreshold {
|
||||
if trade.Size >= largeThreshold {
|
||||
flow.LargeTrades++
|
||||
}
|
||||
}
|
||||
@@ -805,7 +805,7 @@ func (tb *TradeBatcher) Add(trade *client.Trade) {
|
||||
defer tb.mu.Unlock()
|
||||
|
||||
tb.trades = append(tb.trades, trade)
|
||||
if len(tb.trades) >= tb.maxSize {
|
||||
if len(tb.trades) >= tb.maxSize {
|
||||
tb.flushLocked()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,7 +313,7 @@ client = LXDexClient(
|
||||
| Place Order | 2ms | 8ms |
|
||||
| Cancel Order | 1ms | 5ms |
|
||||
| Get Order Book | 1ms | 4ms |
|
||||
| WebSocket Update | <1ms | 2ms |
|
||||
| WebSocket Update | <1ms | 2ms |
|
||||
|
||||
## Support
|
||||
|
||||
|
||||
@@ -239,8 +239,8 @@ print()
|
||||
# Depth analysis
|
||||
print("Depth (1% from mid):")
|
||||
mid = book.mid_price
|
||||
bid_depth_1pct = bids[bids["price"] >= mid * 0.99]["size"].sum()
|
||||
ask_depth_1pct = asks[asks["price"] <= mid * 1.01]["size"].sum()
|
||||
bid_depth_1pct = bids[bids["price"] >= mid * 0.99]["size"].sum()
|
||||
ask_depth_1pct = asks[asks["price"] <= mid * 1.01]["size"].sum()
|
||||
print(f" Bid depth (1%): {bid_depth_1pct:.4f}")
|
||||
print(f" Ask depth (1%): {ask_depth_1pct:.4f}")
|
||||
|
||||
@@ -474,8 +474,8 @@ mid = book.mid_price
|
||||
bid_1pct = mid * 0.99
|
||||
ask_1pct = mid * 1.01
|
||||
|
||||
bid_depth_1pct = bid_sizes[bid_prices >= bid_1pct].sum()
|
||||
ask_depth_1pct = ask_sizes[ask_prices <= ask_1pct].sum()
|
||||
bid_depth_1pct = bid_sizes[bid_prices >= bid_1pct].sum()
|
||||
ask_depth_1pct = ask_sizes[ask_prices <= ask_1pct].sum()
|
||||
|
||||
print(f"Depth to move bid 1%: {bid_depth_1pct:.4f}")
|
||||
print(f"Depth to move ask 1%: {ask_depth_1pct:.4f}")
|
||||
|
||||
@@ -371,7 +371,7 @@ async def stream_trades():
|
||||
f"{trade.size:.4f} @ {trade.price:.2f}")
|
||||
|
||||
# Stop after 100 trades
|
||||
if trade_count >= 100:
|
||||
if trade_count >= 100:
|
||||
print(f"\nTotal volume: {total_volume:.4f}")
|
||||
break
|
||||
|
||||
@@ -551,8 +551,8 @@ print("=== Trade Tape Analysis ===")
|
||||
print(by_class)
|
||||
|
||||
# Large trade detection
|
||||
large_trades = df[df["size"] >= 1.0]
|
||||
print(f"\nLarge trades (>=1.0): {len(large_trades)}")
|
||||
large_trades = df[df["size"] >= 1.0]
|
||||
print(f"\nLarge trades (>=1.0): {len(large_trades)}")
|
||||
print(f"Large trade volume: {large_trades['size'].sum():.4f}")
|
||||
|
||||
# Calculate trade arrival rate
|
||||
|
||||
@@ -547,7 +547,7 @@ pub struct MarginInfo {
|
||||
impl MarginInfo {
|
||||
/// Check if position can be opened
|
||||
pub fn can_open_position(&self, required_margin: f64) -> bool {
|
||||
self.free_margin >= required_margin
|
||||
self.free_margin >= required_margin
|
||||
}
|
||||
|
||||
/// Distance to margin call (percentage)
|
||||
|
||||
@@ -384,7 +384,7 @@ fn process_updates() {
|
||||
```rust
|
||||
/// Memory-compact order book using fixed-point prices
|
||||
pub struct CompactOrderBook {
|
||||
symbol: ArrayString<16>, // Inline string
|
||||
symbol: ArrayString<16>, // Inline string
|
||||
bids: ArrayVec<CompactLevel, 100>,
|
||||
asks: ArrayVec<CompactLevel, 100>,
|
||||
timestamp: i64,
|
||||
@@ -455,12 +455,12 @@ impl OrderBook {
|
||||
let threshold = mid * depth_percent / 100.0;
|
||||
|
||||
let bid_liquidity: f64 = self.bids.iter()
|
||||
.take_while(|l| mid - l.price <= threshold)
|
||||
.take_while(|l| mid - l.price <= threshold)
|
||||
.map(|l| l.size * l.price)
|
||||
.sum();
|
||||
|
||||
let ask_liquidity: f64 = self.asks.iter()
|
||||
.take_while(|l| l.price - mid <= threshold)
|
||||
.take_while(|l| l.price - mid <= threshold)
|
||||
.map(|l| l.size * l.price)
|
||||
.sum();
|
||||
|
||||
@@ -482,7 +482,7 @@ impl OrderBook {
|
||||
total_cost += fill * level.price;
|
||||
remaining -= fill;
|
||||
|
||||
if remaining <= 0.0 {
|
||||
if remaining <= 0.0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ async fn large_trades(client: &Client, min_size: f64) -> Result<()> {
|
||||
|
||||
let mut filtered = stream.filter(|result| {
|
||||
match result {
|
||||
Ok(trade) => trade.size >= min_size,
|
||||
Ok(trade) => trade.size >= min_size,
|
||||
Err(_) => true, // Let errors through
|
||||
}
|
||||
});
|
||||
@@ -240,7 +240,7 @@ impl TradeAggregator {
|
||||
}
|
||||
|
||||
// Check if bucket should be flushed
|
||||
if self.last_flush.elapsed() >= self.bucket_duration {
|
||||
if self.last_flush.elapsed() >= self.bucket_duration {
|
||||
self.flush()
|
||||
} else {
|
||||
None
|
||||
@@ -425,7 +425,7 @@ impl TradeFlowAnalyzer {
|
||||
}
|
||||
|
||||
pub fn add(&mut self, trade: Trade) {
|
||||
if self.window.len() >= self.window_size {
|
||||
if self.window.len() >= self.window_size {
|
||||
self.window.pop_front();
|
||||
}
|
||||
self.window.push_back(trade);
|
||||
|
||||
@@ -296,7 +296,7 @@ function calculateMarketImpact(
|
||||
let levelsConsumed = 0;
|
||||
|
||||
for (const level of levels) {
|
||||
if (remainingSize <= 0) break;
|
||||
if (remainingSize <= 0) break;
|
||||
|
||||
const fillSize = Math.min(remainingSize, level.size);
|
||||
totalCost += fillSize * level.price;
|
||||
|
||||
@@ -605,7 +605,7 @@ async function placeGridOrders(): Promise<void> {
|
||||
const buyOrders: Partial<Order>[] = [];
|
||||
const sellOrders: Partial<Order>[] = [];
|
||||
|
||||
for (let i = 1; i <= gridSize; i++) {
|
||||
for (let i = 1; i <= gridSize; i++) {
|
||||
// Buy orders below current price
|
||||
buyOrders.push({
|
||||
symbol: 'BTC-USD',
|
||||
|
||||
@@ -303,7 +303,7 @@ class HeartbeatClient {
|
||||
this.missedHeartbeats++;
|
||||
console.log(`Missed heartbeat (${this.missedHeartbeats})`);
|
||||
|
||||
if (this.missedHeartbeats >= this.maxMissedHeartbeats) {
|
||||
if (this.missedHeartbeats >= this.maxMissedHeartbeats) {
|
||||
console.log('Connection lost - triggering disconnect');
|
||||
this.stopHeartbeat();
|
||||
this.onDisconnect?.();
|
||||
|
||||
@@ -175,7 +175,7 @@ Apply the Checks-Effects-Interactions pattern:
|
||||
|
||||
```solidity
|
||||
function withdraw(uint256 amount) external {
|
||||
require(balances[msg.sender] >= amount, "Insufficient balance");
|
||||
require(balances[msg.sender] >= amount, "Insufficient balance");
|
||||
|
||||
// Effect: Update state before interaction
|
||||
balances[msg.sender] -= amount;
|
||||
|
||||
@@ -471,7 +471,7 @@ func (m *SignerSetManager) RegisterValidator(
|
||||
})
|
||||
|
||||
// Freeze at max signers
|
||||
if len(m.signerSet.Signers) >= m.maxSigners {
|
||||
if len(m.signerSet.Signers) >= m.maxSigners {
|
||||
m.signerSet.SetFrozen = true
|
||||
}
|
||||
|
||||
@@ -646,7 +646,7 @@ func (d *AnomalyDetector) MonitorSigningSession(session *SigningSession) {
|
||||
// Monitor failures
|
||||
session.OnFailure(func(err error) {
|
||||
d.metrics.FailedAttempts++
|
||||
if d.metrics.FailedAttempts >= d.threshold.MaxFailedAttempts {
|
||||
if d.metrics.FailedAttempts >= d.threshold.MaxFailedAttempts {
|
||||
d.alerter.Alert(AlertRepeatedFailures, map[string]interface{}{
|
||||
"failures": d.metrics.FailedAttempts,
|
||||
"error": err.Error(),
|
||||
|
||||
@@ -49,7 +49,7 @@ contract VulnerableVault {
|
||||
mapping(address => uint256) public balances;
|
||||
|
||||
function withdraw(uint256 amount) external {
|
||||
require(balances[msg.sender] >= amount);
|
||||
require(balances[msg.sender] >= amount);
|
||||
|
||||
// External call BEFORE state update - VULNERABLE
|
||||
(bool success,) = msg.sender.call{value: amount}("");
|
||||
@@ -65,7 +65,7 @@ contract SecureVault {
|
||||
|
||||
function withdraw(uint256 amount) external {
|
||||
// CHECKS
|
||||
require(balances[msg.sender] >= amount, "Insufficient balance");
|
||||
require(balances[msg.sender] >= amount, "Insufficient balance");
|
||||
|
||||
// EFFECTS - Update state BEFORE external call
|
||||
balances[msg.sender] -= amount;
|
||||
@@ -83,7 +83,7 @@ contract GuardedVault is ReentrancyGuard {
|
||||
mapping(address => uint256) public balances;
|
||||
|
||||
function withdraw(uint256 amount) external nonReentrant {
|
||||
require(balances[msg.sender] >= amount, "Insufficient balance");
|
||||
require(balances[msg.sender] >= amount, "Insufficient balance");
|
||||
balances[msg.sender] -= amount;
|
||||
(bool success,) = msg.sender.call{value: amount}("");
|
||||
require(success, "Transfer failed");
|
||||
@@ -118,7 +118,7 @@ contract SecureToken {
|
||||
mapping(address => uint256) public balances;
|
||||
|
||||
function transfer(address to, uint256 amount) external {
|
||||
require(balances[msg.sender] >= amount, "Insufficient balance");
|
||||
require(balances[msg.sender] >= amount, "Insufficient balance");
|
||||
|
||||
// Solidity 0.8+ reverts on overflow/underflow automatically
|
||||
balances[msg.sender] -= amount;
|
||||
@@ -242,12 +242,12 @@ contract MultiBlockProtection {
|
||||
|
||||
function executeAction() external {
|
||||
PriceCheckpoint memory cp = checkpoints[msg.sender];
|
||||
require(block.number >= cp.blockNumber + MIN_BLOCKS, "Too soon");
|
||||
require(block.number >= cp.blockNumber + MIN_BLOCKS, "Too soon");
|
||||
|
||||
uint256 currentPrice = getPrice();
|
||||
require(
|
||||
currentPrice >= cp.price * 99 / 100 &&
|
||||
currentPrice <= cp.price * 101 / 100,
|
||||
currentPrice >= cp.price * 99 / 100 &&
|
||||
currentPrice <= cp.price * 101 / 100,
|
||||
"Price deviation"
|
||||
);
|
||||
|
||||
@@ -279,7 +279,7 @@ contract SecureOracle {
|
||||
) = chainlinkOracle.latestRoundData();
|
||||
|
||||
require(chainlinkPrice > 0, "Invalid Chainlink price");
|
||||
require(answeredInRound >= roundId, "Stale Chainlink data");
|
||||
require(answeredInRound >= roundId, "Stale Chainlink data");
|
||||
require(
|
||||
block.timestamp - updatedAt < STALENESS_THRESHOLD,
|
||||
"Chainlink data too old"
|
||||
@@ -295,7 +295,7 @@ contract SecureOracle {
|
||||
? (primaryPrice - twapPrice) * 100 / primaryPrice
|
||||
: (twapPrice - primaryPrice) * 100 / twapPrice;
|
||||
|
||||
require(deviation <= MAX_DEVIATION, "Oracle price deviation");
|
||||
require(deviation <= MAX_DEVIATION, "Oracle price deviation");
|
||||
|
||||
return primaryPrice;
|
||||
}
|
||||
@@ -350,7 +350,7 @@ contract CommitRevealOrder {
|
||||
Commitment storage c = commitments[msg.sender];
|
||||
|
||||
require(!c.revealed, "Already revealed");
|
||||
require(block.number >= c.blockNumber + REVEAL_DELAY, "Too early");
|
||||
require(block.number >= c.blockNumber + REVEAL_DELAY, "Too early");
|
||||
|
||||
bytes32 expectedHash = keccak256(
|
||||
abi.encodePacked(msg.sender, amount, price, isBuy, salt)
|
||||
@@ -416,7 +416,7 @@ contract SecureSignatures {
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) external {
|
||||
require(block.timestamp <= deadline, "Order expired");
|
||||
require(block.timestamp <= deadline, "Order expired");
|
||||
|
||||
bytes32 structHash = keccak256(abi.encode(
|
||||
ORDER_TYPEHASH,
|
||||
@@ -504,7 +504,7 @@ contract EmergencyControl is Pausable, AccessControl {
|
||||
function executeUnpause() external onlyRole(UNPAUSER_ROLE) {
|
||||
require(unpauseRequestTime != 0, "No request");
|
||||
require(
|
||||
block.timestamp >= unpauseRequestTime + UNPAUSE_DELAY,
|
||||
block.timestamp >= unpauseRequestTime + UNPAUSE_DELAY,
|
||||
"Timelock active"
|
||||
);
|
||||
|
||||
@@ -569,7 +569,7 @@ contract SecureUpgradeable is Initializable, UUPSUpgradeable, AccessControl {
|
||||
{
|
||||
require(newImplementation == pendingImplementation, "Wrong implementation");
|
||||
require(
|
||||
block.timestamp >= upgradeRequestTime + UPGRADE_DELAY,
|
||||
block.timestamp >= upgradeRequestTime + UPGRADE_DELAY,
|
||||
"Timelock active"
|
||||
);
|
||||
|
||||
|
||||
@@ -18,14 +18,11 @@ The LP-0100 series defines consensus mechanisms for the Lux Network, including P
|
||||
|
||||
---
|
||||
|
||||
## LP-0111: Photon Consensus {#lp-0111}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-0111-photon-consensus.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-0111" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/consensus" />
|
||||
</Cards>
|
||||
## LP-0111: Photon Consensus
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-0111-photon-consensus.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-0111)
|
||||
- [**Implementation**](https://github.com/luxfi/consensus)
|
||||
### Abstract
|
||||
|
||||
LP-0111 defines Photon, the primary chain consensus mechanism for Lux Network. Photon achieves sub-second finality with Byzantine fault tolerance up to 1/3 of validators.
|
||||
@@ -121,14 +118,11 @@ engine.Start(ctx)
|
||||
|
||||
---
|
||||
|
||||
## LP-0112: Flare DAG Consensus {#lp-0112}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-0112-flare-dag-consensus.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-0112" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/consensus/tree/main/dag" />
|
||||
</Cards>
|
||||
## LP-0112: Flare DAG Consensus
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-0112-flare-dag-consensus.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-0112)
|
||||
- [**Implementation**](https://github.com/luxfi/consensus/tree/main/dag)
|
||||
### Abstract
|
||||
|
||||
LP-0112 defines Flare, a DAG-based consensus mechanism for high-throughput parallel transaction processing. Flare enables multiple blocks to be processed simultaneously while maintaining total ordering.
|
||||
@@ -201,14 +195,11 @@ type ConflictResolver interface {
|
||||
|
||||
---
|
||||
|
||||
## LP-0120: FPC Fast Finality {#lp-0120}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-0120-fpc-fast-finality.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-0120" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/consensus/tree/main/fpc" />
|
||||
</Cards>
|
||||
## LP-0120: FPC Fast Finality
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-0120-fpc-fast-finality.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-0120)
|
||||
- [**Implementation**](https://github.com/luxfi/consensus/tree/main/fpc)
|
||||
### Abstract
|
||||
|
||||
LP-0120 defines Fast Probabilistic Consensus (FPC), a Byzantine agreement protocol achieving 1ms finality through repeated random sampling of validators.
|
||||
@@ -241,17 +232,17 @@ FOR round IN 1..MAX_ROUNDS:
|
||||
no_count = Count(votes, 0)
|
||||
|
||||
// Update opinion based on threshold
|
||||
IF yes_count >= THRESHOLD:
|
||||
IF yes_count >= THRESHOLD:
|
||||
opinion = 1
|
||||
confidence++
|
||||
ELSE IF no_count >= THRESHOLD:
|
||||
ELSE IF no_count >= THRESHOLD:
|
||||
opinion = 0
|
||||
confidence++
|
||||
ELSE:
|
||||
confidence = 0 // Reset on tie
|
||||
|
||||
// Check for finality
|
||||
IF confidence >= FINALITY_THRESHOLD:
|
||||
IF confidence >= FINALITY_THRESHOLD:
|
||||
RETURN opinion // Finalized!
|
||||
|
||||
RETURN UNDECIDED
|
||||
@@ -284,14 +275,11 @@ type FPCConfig struct {
|
||||
|
||||
---
|
||||
|
||||
## LP-4099: Quasar Post-Quantum Consensus {#lp-4099}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-4099-quasar-pq-consensus.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-4099" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/consensus/tree/main/pq" />
|
||||
</Cards>
|
||||
## LP-4099: Quasar Post-Quantum Consensus
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-4099-quasar-pq-consensus.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-4099)
|
||||
- [**Implementation**](https://github.com/luxfi/consensus/tree/main/pq)
|
||||
### Abstract
|
||||
|
||||
LP-4099 defines Quasar, a post-quantum consensus mechanism using lattice-based signatures (Dilithium/Corona) for quantum-resistant validator attestations.
|
||||
|
||||
@@ -22,14 +22,11 @@ The LP-9000 series defines the complete specification for the LX Decentralized E
|
||||
|
||||
---
|
||||
|
||||
## LP-9000: DEX Core Specification {#lp-9000}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-9000-dex-core-specification.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-9000" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/dex" />
|
||||
</Cards>
|
||||
## LP-9000: DEX Core Specification
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-9000-dex-core-specification.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-9000)
|
||||
- [**Implementation**](https://github.com/luxfi/dex)
|
||||
### Abstract
|
||||
|
||||
LP-9000 defines the core architecture and requirements for the LX Decentralized Exchange, a high-performance trading platform achieving 434M+ orders/sec with sub-microsecond latency.
|
||||
@@ -92,14 +89,11 @@ LP-9000 defines the core architecture and requirements for the LX Decentralized
|
||||
|
||||
---
|
||||
|
||||
## LP-9001: Trading Engine {#lp-9001}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-9001-dex-trading-engine.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-9001" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/dex/tree/main/pkg/lx" />
|
||||
</Cards>
|
||||
## LP-9001: Trading Engine
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-9001-dex-trading-engine.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-9001)
|
||||
- [**Implementation**](https://github.com/luxfi/dex/tree/main/pkg/lx)
|
||||
### Abstract
|
||||
|
||||
LP-9001 specifies the multi-engine trading architecture supporting Pure Go, C++, and GPU acceleration for maximum performance across different hardware configurations.
|
||||
@@ -147,14 +141,11 @@ type Engine interface {
|
||||
|
||||
---
|
||||
|
||||
## LP-9002: DEX API/RPC Specification {#lp-9002}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-9002-dex-api-rpc-specification.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-9002" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/dex/tree/main/pkg/api" />
|
||||
</Cards>
|
||||
## LP-9002: DEX API/RPC Specification
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-9002-dex-api-rpc-specification.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-9002)
|
||||
- [**Implementation**](https://github.com/luxfi/dex/tree/main/pkg/api)
|
||||
### Abstract
|
||||
|
||||
LP-9002 defines the complete API specification for interacting with the LX DEX, including JSON-RPC, gRPC, WebSocket, REST, and FIX protocols.
|
||||
@@ -236,14 +227,11 @@ LP-9002 defines the complete API specification for interacting with the LX DEX,
|
||||
|
||||
---
|
||||
|
||||
## LP-9003: High-Performance Protocol {#lp-9003}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-9003-high-performance-dex-protocol.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-9003" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/dex/tree/main/pkg/engine" />
|
||||
</Cards>
|
||||
## LP-9003: High-Performance Protocol
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-9003-high-performance-dex-protocol.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-9003)
|
||||
- [**Implementation**](https://github.com/luxfi/dex/tree/main/pkg/engine)
|
||||
### Abstract
|
||||
|
||||
LP-9003 specifies the low-level binary protocol and optimizations for achieving sub-microsecond latency in high-frequency trading scenarios.
|
||||
@@ -290,14 +278,11 @@ LP-9003 specifies the low-level binary protocol and optimizations for achieving
|
||||
|
||||
---
|
||||
|
||||
## LP-9010: Orderbook Specification {#lp-9010}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-9010-orderbook-specification.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-9010" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/dex/tree/main/pkg/orderbook" />
|
||||
</Cards>
|
||||
## LP-9010: Orderbook Specification
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-9010-orderbook-specification.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-9010)
|
||||
- [**Implementation**](https://github.com/luxfi/dex/tree/main/pkg/orderbook)
|
||||
### Abstract
|
||||
|
||||
LP-9010 defines the orderbook data structure, price level management, and order priority rules for the LX DEX.
|
||||
@@ -334,14 +319,11 @@ type PriceLevel struct {
|
||||
|
||||
---
|
||||
|
||||
## LP-9020: Matching Engine {#lp-9020}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-9020-matching-engine.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-9020" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/dex/tree/main/pkg/matching" />
|
||||
</Cards>
|
||||
## LP-9020: Matching Engine
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-9020-matching-engine.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-9020)
|
||||
- [**Implementation**](https://github.com/luxfi/dex/tree/main/pkg/matching)
|
||||
### Abstract
|
||||
|
||||
LP-9020 specifies the order matching algorithm, execution rules, and trade generation for the LX DEX.
|
||||
@@ -392,14 +374,11 @@ MATCH(order):
|
||||
|
||||
---
|
||||
|
||||
## LP-9030: Market Data Protocol {#lp-9030}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-9030-market-data-protocol.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-9030" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/dex/tree/main/pkg/feed" />
|
||||
</Cards>
|
||||
## LP-9030: Market Data Protocol
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-9030-market-data-protocol.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-9030)
|
||||
- [**Implementation**](https://github.com/luxfi/dex/tree/main/pkg/feed)
|
||||
### Abstract
|
||||
|
||||
LP-9030 defines the market data distribution protocol, including real-time feeds, historical data, and aggregation methods.
|
||||
@@ -408,9 +387,9 @@ LP-9030 defines the market data distribution protocol, including real-time feeds
|
||||
|
||||
| Feed | Latency | Update Rate | Use Case |
|
||||
|------|---------|-------------|----------|
|
||||
| Level 1 | <1ms | Every trade | Retail |
|
||||
| Level 2 | <1ms | Every change | Active traders |
|
||||
| Level 3 | <100us | Every message | Market makers |
|
||||
| Level 1 | <1ms | Every trade | Retail |
|
||||
| Level 2 | <1ms | Every change | Active traders |
|
||||
| Level 3 | <100us | Every message | Market makers |
|
||||
| OHLCV | 1s | Per interval | Analytics |
|
||||
|
||||
### Related LPs
|
||||
@@ -420,14 +399,11 @@ LP-9030 defines the market data distribution protocol, including real-time feeds
|
||||
|
||||
---
|
||||
|
||||
## LP-9040: Settlement Protocol {#lp-9040}
|
||||
|
||||
<Cards>
|
||||
<Card title="Full Specification" href="https://github.com/luxfi/LPs/blob/main/LPs/lp-9040-settlement-protocol.md" />
|
||||
<Card title="Discussion" href="https://github.com/luxfi/LPs/discussions/categories/lp-9040" />
|
||||
<Card title="Implementation" href="https://github.com/luxfi/dex/tree/main/pkg/settlement" />
|
||||
</Cards>
|
||||
## LP-9040: Settlement Protocol
|
||||
|
||||
- [**Full Specification**](https://github.com/luxfi/LPs/blob/main/LPs/lp-9040-settlement-protocol.md)
|
||||
- [**Discussion**](https://github.com/luxfi/LPs/discussions/categories/lp-9040)
|
||||
- [**Implementation**](https://github.com/luxfi/dex/tree/main/pkg/settlement)
|
||||
### Abstract
|
||||
|
||||
LP-9040 specifies the settlement protocol for finalizing trades on-chain using Warp messages and atomic swaps.
|
||||
|
||||
@@ -9,12 +9,9 @@ Lux Proposals (LPs) are the formal specification mechanism for all technical sta
|
||||
|
||||
## LP Repository
|
||||
|
||||
<Cards>
|
||||
<Card title="LP Repository" href="https://github.com/luxfi/LPs" />
|
||||
<Card title="Discussions" href="https://github.com/luxfi/LPs/discussions" />
|
||||
<Card title="Submit LP" href="https://github.com/luxfi/LPs/issues/new?template=lp-proposal.md" />
|
||||
</Cards>
|
||||
|
||||
- [**LP Repository**](https://github.com/luxfi/LPs)
|
||||
- [**Discussions**](https://github.com/luxfi/LPs/discussions)
|
||||
- [**Submit LP**](https://github.com/luxfi/LPs/issues/new?template=lp-proposal.md)
|
||||
## LP Categories
|
||||
|
||||
| Category | Range | Description | Count |
|
||||
|
||||
@@ -69,8 +69,8 @@ curl -X POST https://faucet.testnet.lux.network/api/request \
|
||||
|
||||
### SDK Request
|
||||
|
||||
<Tabs items={['TypeScript', 'Python', 'Go']}>
|
||||
<Tab value="TypeScript">
|
||||
#### TypeScript
|
||||
|
||||
```typescript
|
||||
import { LXDexClient } from '@luxfi/dex-sdk';
|
||||
|
||||
@@ -90,8 +90,9 @@ const allowance = await client.faucet.getAllowance({
|
||||
});
|
||||
console.log('Remaining today:', allowance);
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
|
||||
#### Python
|
||||
|
||||
```python
|
||||
from luxfi_dex import LXDexClient
|
||||
|
||||
@@ -109,8 +110,9 @@ print(f"Received: {result.amounts}")
|
||||
allowance = client.faucet.get_allowance(address='your_wallet_address')
|
||||
print(f"Remaining today: {allowance}")
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Go">
|
||||
|
||||
#### Go
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
@@ -136,8 +138,6 @@ func main() {
|
||||
fmt.Printf("Remaining today: %+v\n", allowance)
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Rate Limits
|
||||
|
||||
|
||||
@@ -214,17 +214,7 @@ jobs:
|
||||
|
||||
## Next Steps
|
||||
|
||||
<Cards>
|
||||
<Card title="Quickstart" href="/docs/testnet/quickstart">
|
||||
Get trading on testnet in 5 minutes
|
||||
</Card>
|
||||
<Card title="Faucet" href="/docs/testnet/faucet">
|
||||
Get free test tokens
|
||||
</Card>
|
||||
<Card title="Endpoints" href="/docs/testnet/endpoints">
|
||||
Complete API endpoint reference
|
||||
</Card>
|
||||
<Card title="Markets" href="/docs/testnet/markets">
|
||||
Available trading pairs
|
||||
</Card>
|
||||
</Cards>
|
||||
- [**Quickstart**](/docs/testnet/quickstart): Get trading on testnet in 5 minutes
|
||||
- [**Faucet**](/docs/testnet/faucet): Get free test tokens
|
||||
- [**Endpoints**](/docs/testnet/endpoints): Complete API endpoint reference
|
||||
- [**Markets**](/docs/testnet/markets): Available trading pairs
|
||||
|
||||
@@ -17,8 +17,8 @@ Get from zero to your first trade on LX DEX Testnet in under 5 minutes.
|
||||
|
||||
Choose your preferred language:
|
||||
|
||||
<Tabs items={['TypeScript', 'Python', 'Go', 'curl']}>
|
||||
<Tab value="TypeScript">
|
||||
#### TypeScript
|
||||
|
||||
```bash
|
||||
npm install @luxfi/dex-sdk
|
||||
# or
|
||||
@@ -26,30 +26,27 @@ pnpm add @luxfi/dex-sdk
|
||||
# or
|
||||
yarn add @luxfi/dex-sdk
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
#### Python
|
||||
|
||||
```bash
|
||||
pip install luxfi-dex
|
||||
# or
|
||||
uv pip install luxfi-dex
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Go">
|
||||
#### Go
|
||||
|
||||
```bash
|
||||
go get github.com/luxfi/dex/sdk/go/lxdex@latest
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="curl">
|
||||
No installation needed - curl comes pre-installed on most systems.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
#### curl
|
||||
|
||||
No installation needed - curl comes pre-installed on most systems.
|
||||
## Step 2: Get Test Tokens (1 minute)
|
||||
|
||||
Request free test tokens from the faucet:
|
||||
|
||||
<Tabs items={['TypeScript', 'Python', 'Go', 'curl']}>
|
||||
<Tab value="TypeScript">
|
||||
#### TypeScript
|
||||
|
||||
```typescript
|
||||
import { LXDexClient } from '@luxfi/dex-sdk';
|
||||
|
||||
@@ -64,8 +61,8 @@ const result = await client.faucet.request({
|
||||
console.log('Tokens received:', result.amounts);
|
||||
// { tLUX: 1000, tUSDC: 100000, tBTC: 1 }
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
#### Python
|
||||
|
||||
```python
|
||||
from luxfi_dex import LXDexClient
|
||||
|
||||
@@ -80,8 +77,8 @@ result = client.faucet.request(
|
||||
print(f"Tokens received: {result.amounts}")
|
||||
# {'tLUX': 1000, 'tUSDC': 100000, 'tBTC': 1}
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Go">
|
||||
#### Go
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
@@ -102,8 +99,8 @@ func main() {
|
||||
fmt.Printf("Tokens received: %+v\n", result.Amounts)
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="curl">
|
||||
#### curl
|
||||
|
||||
```bash
|
||||
curl -X POST https://faucet.testnet.lux.network/api/request \
|
||||
-H "Content-Type: application/json" \
|
||||
@@ -125,15 +122,12 @@ Response:
|
||||
"txHash": "0x123..."
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Step 3: Check Your Balance (30 seconds)
|
||||
|
||||
Verify tokens were received:
|
||||
|
||||
<Tabs items={['TypeScript', 'Python', 'Go', 'curl']}>
|
||||
<Tab value="TypeScript">
|
||||
#### TypeScript
|
||||
|
||||
```typescript
|
||||
const balances = await client.getBalances();
|
||||
console.log('Balances:', balances);
|
||||
@@ -143,21 +137,21 @@ console.log('Balances:', balances);
|
||||
// tBTC: 1
|
||||
// }
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
#### Python
|
||||
|
||||
```python
|
||||
balances = client.get_balances()
|
||||
print(f"Balances: {balances}")
|
||||
# {'tLUX': 1000, 'tUSDC': 100000, 'tBTC': 1}
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Go">
|
||||
#### Go
|
||||
|
||||
```go
|
||||
balances, _ := client.GetBalances(context.Background())
|
||||
fmt.Printf("Balances: %+v\n", balances)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="curl">
|
||||
#### curl
|
||||
|
||||
```bash
|
||||
curl -X POST https://testnet-api.lux.network/rpc \
|
||||
-H "Content-Type: application/json" \
|
||||
@@ -168,15 +162,12 @@ curl -X POST https://testnet-api.lux.network/rpc \
|
||||
"id": 1
|
||||
}'
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Step 4: View Order Book (30 seconds)
|
||||
|
||||
Check the current market state:
|
||||
|
||||
<Tabs items={['TypeScript', 'Python', 'Go', 'curl']}>
|
||||
<Tab value="TypeScript">
|
||||
#### TypeScript
|
||||
|
||||
```typescript
|
||||
const orderBook = await client.getOrderBook({
|
||||
symbol: 'tBTC-tUSDC',
|
||||
@@ -186,16 +177,16 @@ const orderBook = await client.getOrderBook({
|
||||
console.log('Best Bid:', orderBook.bids[0]);
|
||||
console.log('Best Ask:', orderBook.asks[0]);
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
#### Python
|
||||
|
||||
```python
|
||||
order_book = client.get_order_book(symbol='tBTC-tUSDC', depth=10)
|
||||
|
||||
print(f"Best Bid: {order_book.bids[0]}")
|
||||
print(f"Best Ask: {order_book.asks[0]}")
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Go">
|
||||
#### Go
|
||||
|
||||
```go
|
||||
orderBook, _ := client.GetOrderBook(context.Background(), &lxdex.OrderBookRequest{
|
||||
Symbol: "tBTC-tUSDC",
|
||||
@@ -205,8 +196,8 @@ orderBook, _ := client.GetOrderBook(context.Background(), &lxdex.OrderBookReques
|
||||
fmt.Printf("Best Bid: %+v\n", orderBook.Bids[0])
|
||||
fmt.Printf("Best Ask: %+v\n", orderBook.Asks[0])
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="curl">
|
||||
#### curl
|
||||
|
||||
```bash
|
||||
curl -X POST https://testnet-api.lux.network/rpc \
|
||||
-H "Content-Type: application/json" \
|
||||
@@ -217,15 +208,12 @@ curl -X POST https://testnet-api.lux.network/rpc \
|
||||
"id": 1
|
||||
}'
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Step 5: Place Your First Order (1 minute)
|
||||
|
||||
Place a limit buy order:
|
||||
|
||||
<Tabs items={['TypeScript', 'Python', 'Go', 'curl']}>
|
||||
<Tab value="TypeScript">
|
||||
#### TypeScript
|
||||
|
||||
```typescript
|
||||
const order = await client.placeOrder({
|
||||
symbol: 'tBTC-tUSDC',
|
||||
@@ -240,8 +228,8 @@ console.log('Order placed!');
|
||||
console.log('Order ID:', order.orderId);
|
||||
console.log('Status:', order.status);
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
#### Python
|
||||
|
||||
```python
|
||||
order = client.place_order(
|
||||
symbol='tBTC-tUSDC',
|
||||
@@ -256,8 +244,8 @@ print("Order placed!")
|
||||
print(f"Order ID: {order.order_id}")
|
||||
print(f"Status: {order.status}")
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Go">
|
||||
#### Go
|
||||
|
||||
```go
|
||||
order, _ := client.PlaceOrder(context.Background(), &lxdex.Order{
|
||||
Symbol: "tBTC-tUSDC",
|
||||
@@ -272,8 +260,8 @@ fmt.Println("Order placed!")
|
||||
fmt.Printf("Order ID: %s\n", order.OrderID)
|
||||
fmt.Printf("Status: %s\n", order.Status)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="curl">
|
||||
#### curl
|
||||
|
||||
```bash
|
||||
curl -X POST https://testnet-api.lux.network/rpc \
|
||||
-H "Content-Type: application/json" \
|
||||
@@ -309,15 +297,12 @@ Response:
|
||||
"id": 1
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Step 6: Monitor Your Order (1 minute)
|
||||
|
||||
Check order status and subscribe to updates:
|
||||
|
||||
<Tabs items={['TypeScript', 'Python', 'Go', 'curl']}>
|
||||
<Tab value="TypeScript">
|
||||
#### TypeScript
|
||||
|
||||
```typescript
|
||||
// Get order status
|
||||
const status = await client.getOrder(order.orderId);
|
||||
@@ -330,8 +315,8 @@ client.subscribe('orders', (update) => {
|
||||
}
|
||||
});
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
#### Python
|
||||
|
||||
```python
|
||||
# Get order status
|
||||
status = client.get_order(order.order_id)
|
||||
@@ -344,8 +329,8 @@ def on_order_update(update):
|
||||
|
||||
client.subscribe('orders', callback=on_order_update)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Go">
|
||||
#### Go
|
||||
|
||||
```go
|
||||
// Get order status
|
||||
status, _ := client.GetOrder(context.Background(), order.OrderID)
|
||||
@@ -358,8 +343,8 @@ client.Subscribe("orders", func(update *lxdex.OrderUpdate) {
|
||||
}
|
||||
})
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="curl">
|
||||
#### curl
|
||||
|
||||
```bash
|
||||
# Get order status
|
||||
curl -X POST https://testnet-api.lux.network/rpc \
|
||||
@@ -374,9 +359,6 @@ curl -X POST https://testnet-api.lux.network/rpc \
|
||||
# For real-time updates, connect to WebSocket:
|
||||
# wss://testnet-api.lux.network/ws
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Complete Example
|
||||
|
||||
Here's a full working example that combines all steps:
|
||||
|
||||
@@ -118,8 +118,8 @@ const order = await dex.placeOrder({
|
||||
**Trigger Conditions:**
|
||||
| Order Side | Trigger Condition |
|
||||
|------------|------------------|
|
||||
| Sell Stop | Last price <= Stop price |
|
||||
| Buy Stop | Last price >= Stop price |
|
||||
| Sell Stop | Last price <= Stop price |
|
||||
| Buy Stop | Last price >= Stop price |
|
||||
|
||||
**Example Scenario:**
|
||||
```
|
||||
|
||||
@@ -248,7 +248,7 @@ async function setupGrid(
|
||||
) {
|
||||
const orders = []
|
||||
|
||||
for (let i = 1; i <= levels; i++) {
|
||||
for (let i = 1; i <= levels; i++) {
|
||||
// Buy orders below center
|
||||
const buyPrice = centerPrice - (gridSize * i)
|
||||
orders.push(dex.spot.buy({
|
||||
|
||||
@@ -237,7 +237,7 @@ func checkOrderBook(ctx context.Context, client *lxdex.Client) {
|
||||
|
||||
fmt.Println("\n=== BTC-USD Order Book ===")
|
||||
fmt.Println("\nAsks (Sell Orders):")
|
||||
for i := len(book.Asks) - 1; i >= 0; i-- {
|
||||
for i := len(book.Asks) - 1; i >= 0; i-- {
|
||||
ask := book.Asks[i]
|
||||
fmt.Printf(" %.2f | %.4f BTC\n", ask.Price, ask.Size)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,25 @@
|
||||
import type { MDXComponents } from "mdx/types"
|
||||
import defaultMdxComponents from "fumadocs-ui/mdx"
|
||||
import { Tab, Tabs } from "fumadocs-ui/components/tabs"
|
||||
import { Card, Cards } from "fumadocs-ui/components/card"
|
||||
import { Step, Steps } from "fumadocs-ui/components/steps"
|
||||
import { Callout } from "fumadocs-ui/components/callout"
|
||||
import { Accordion, Accordions } from "fumadocs-ui/components/accordion"
|
||||
import { TypeTable } from "fumadocs-ui/components/type-table"
|
||||
|
||||
export function useMDXComponents(components: MDXComponents): MDXComponents {
|
||||
return {
|
||||
...defaultMdxComponents,
|
||||
Tab,
|
||||
Tabs,
|
||||
Card,
|
||||
Cards,
|
||||
Step,
|
||||
Steps,
|
||||
Callout,
|
||||
Accordion,
|
||||
Accordions,
|
||||
TypeTable,
|
||||
...components,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user