代码示例与语法高亮

本文展示了不同编程语言代码块的语法高亮和复制功能。每个代码块右上角都有一个复制按钮,方便用户快速复制代码。

JavaScript 示例

以下是一个简单的 JavaScript 函数示例:

// 计算斐波那契数列
function fibonacci(n) {
  if (n <= 1) {
    return n;
  }
  
  return fibonacci(n - 1) + fibonacci(n - 2);
}

// 测试函数
console.log("斐波那契数列的前10个数:");
for (let i = 0; i < 10; i++) {
  console.log(`fibonacci(${i}) = ${fibonacci(i)}`);
}

Python 示例

这是一个 Python 类的示例:

class TradingStrategy:
    """
    简单的交易策略类
    """
    def __init__(self, name, parameters=None):
        self.name = name
        self.parameters = parameters or {}
        self.positions = []
        
    def calculate_signal(self, price_data):
        """
        根据价格数据计算交易信号
        """
        if not price_data or len(price_data) < 2:
            return "HOLD"
            
        current_price = price_data[-1]
        previous_price = price_data[-2]
        
        if current_price > previous_price * 1.05:  # 上涨5%
            return "BUY"
        elif current_price < previous_price * 0.95:  # 下跌5%
            return "SELL"
        else:
            return "HOLD"
    
    def execute_trade(self, signal, price, quantity):
        """
        执行交易
        """
        if signal == "BUY":
            self.positions.append({"price": price, "quantity": quantity})
            print(f"买入 {quantity} 单位,价格:{price}")
        elif signal == "SELL" and self.positions:
            position = self.positions.pop(0)
            profit = (price - position["price"]) * position["quantity"]
            print(f"卖出 {position['quantity']} 单位,价格:{price},盈亏:{profit}")

TypeScript 示例

TypeScript 代码示例,展示了接口和类型:

// 定义交易数据接口
interface TradeData {
  symbol: string;
  price: number;
  quantity: number;
  side: 'BUY' | 'SELL';
  timestamp: Date;
}

// 定义交易结果类型
type TradeResult = {
  success: boolean;
  orderId?: string;
  error?: string;
  executedPrice?: number;
};

// 交易服务类
class TradeService {
  private apiKey: string;
  private apiSecret: string;
  
  constructor(apiKey: string, apiSecret: string) {
    this.apiKey = apiKey;
    this.apiSecret = apiSecret;
  }
  
  async executeTrade(data: TradeData): Promise<TradeResult> {
    try {
      // 这里是实际执行交易的代码
      console.log(`执行${data.side}交易: ${data.symbol}, 价格: ${data.price}, 数量: ${data.quantity}`);
      
      return {
        success: true,
        orderId: `ORD-${Date.now()}`,
        executedPrice: data.price
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }
}

C++ 示例

#include <iostream>
#include <vector>
#include <algorithm>

// 计算移动平均线
class MovingAverage {
private:
    std::vector<double> values;
    size_t period;
    
public:
    MovingAverage(size_t p) : period(p) {}
    
    double calculate(double newValue) {
        // 添加新值
        values.push_back(newValue);
        
        // 如果数据超过周期长度,移除最旧的数据
        if (values.size() > period) {
            values.erase(values.begin());
        }
        
        // 计算平均值
        double sum = 0;
        for (const auto& value : values) {
            sum += value;
        }
        
        return sum / values.size();
    }
};

int main() {
    MovingAverage ma5(5);  // 5周期移动平均线
    
    // 测试数据
    std::vector<double> prices = {100.0, 102.5, 99.8, 101.3, 105.2, 103.7, 106.1, 108.4};
    
    std::cout << "价格 -> 5周期移动平均线" << std::endl;
    for (const auto& price : prices) {
        double avg = ma5.calculate(price);
        std::cout << price << " -> " << avg << std::endl;
    }
    
    return 0;
}

SQL 示例

-- 创建交易表
CREATE TABLE trades (
    id SERIAL PRIMARY KEY,
    symbol VARCHAR(10) NOT NULL,
    trade_type VARCHAR(4) CHECK (trade_type IN ('BUY', 'SELL')),
    price DECIMAL(10, 2) NOT NULL,
    quantity INTEGER NOT NULL,
    trade_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    user_id INTEGER REFERENCES users(id)
);

-- 插入示例数据
INSERT INTO trades (symbol, trade_type, price, quantity, user_id)
VALUES 
    ('AAPL', 'BUY', 150.25, 10, 1),
    ('MSFT', 'BUY', 290.45, 5, 1),
    ('GOOGL', 'SELL', 2750.80, 2, 2),
    ('AAPL', 'SELL', 155.75, 5, 1);

-- 查询用户的交易盈亏
SELECT 
    u.username,
    t.symbol,
    SUM(CASE WHEN t.trade_type = 'BUY' THEN -t.price * t.quantity
             WHEN t.trade_type = 'SELL' THEN t.price * t.quantity
             ELSE 0 END) AS profit_loss
FROM 
    trades t
JOIN 
    users u ON t.user_id = u.id
GROUP BY 
    u.username, t.symbol
ORDER BY 
    profit_loss DESC;

HTML/CSS 示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>交易面板</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .trading-panel {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }
        
        .panel-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        
        .symbol-info {
            display: flex;
            align-items: center;
        }
        
        .symbol-name {
            font-size: 24px;
            font-weight: bold;
            margin-right: 10px;
        }
        
        .price {
            font-size: 22px;
            color: #d9534f;
        }
        
        .trading-form {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        input, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        
        .btn {
            padding: 12px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: background-color 0.3s;
        }
        
        .btn-buy {
            background-color: #5cb85c;
            color: white;
        }
        
        .btn-sell {
            background-color: #d9534f;
            color: white;
        }
    </style>
</head>
<body>
    <div class="trading-panel">
        <div class="panel-header">
            <div class="symbol-info">
                <div class="symbol-name">AAPL</div>
                <div class="price">$152.37</div>
            </div>
            <div class="change">+1.25 (0.83%)</div>
        </div>
        
        <div class="trading-form">
            <div>
                <div class="form-group">
                    <label for="order-type">订单类型</label>
                    <select id="order-type">
                        <option>市价单</option>
                        <option>限价单</option>
                        <option>止损单</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="quantity">数量</label>
                    <input type="number" id="quantity" min="1" value="1">
                </div>
            </div>
            
            <div>
                <div class="form-group">
                    <label for="price">价格</label>
                    <input type="number" id="price" step="0.01" value="152.37">
                </div>
                
                <div class="form-group">
                    <label for="total">总额</label>
                    <input type="text" id="total" readonly value="$152.37">
                </div>
            </div>
        </div>
        
        <div style="display: flex; gap: 10px; margin-top: 20px;">
            <button class="btn btn-buy">买入</button>
            <button class="btn btn-sell">卖出</button>
        </div>
    </div>
</body>
</html>

Java 示例

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单管理系统
 */
public class OrderManagementSystem {
    
    private List<Order> orders;
    
    public OrderManagementSystem() {
        this.orders = new ArrayList<>();
    }
    
    /**
     * 创建新订单
     */
    public Order createOrder(String symbol, double price, int quantity, OrderType type) {
        Order order = new Order(
            generateOrderId(),
            symbol,
            price,
            quantity,
            type,
            OrderStatus.PENDING,
            new Date()
        );
        
        orders.add(order);
        System.out.println("创建订单: " + order);
        return order;
    }
    
    /**
     * 执行订单
     */
    public boolean executeOrder(String orderId) {
        for (Order order : orders) {
            if (order.getOrderId().equals(orderId)) {
                if (order.getStatus() == OrderStatus.PENDING) {
                    order.setStatus(OrderStatus.EXECUTED);
                    order.setExecutionTime(new Date());
                    System.out.println("执行订单: " + order);
                    return true;
                } else {
                    System.out.println("订单无法执行,当前状态: " + order.getStatus());
                    return false;
                }
            }
        }
        
        System.out.println("未找到订单: " + orderId);
        return false;
    }
    
    /**
     * 取消订单
     */
    public boolean cancelOrder(String orderId) {
        for (Order order : orders) {
            if (order.getOrderId().equals(orderId)) {
                if (order.getStatus() == OrderStatus.PENDING) {
                    order.setStatus(OrderStatus.CANCELLED);
                    System.out.println("取消订单: " + order);
                    return true;
                } else {
                    System.out.println("订单无法取消,当前状态: " + order.getStatus());
                    return false;
                }
            }
        }
        
        System.out.println("未找到订单: " + orderId);
        return false;
    }
    
    /**
     * 生成订单ID
     */
    private String generateOrderId() {
        return "ORD-" + System.currentTimeMillis();
    }
    
    /**
     * 获取所有订单
     */
    public List<Order> getAllOrders() {
        return new ArrayList<>(orders);
    }
    
    /**
     * 订单实体类
     */
    public static class Order {
        private String orderId;
        private String symbol;
        private double price;
        private int quantity;
        private OrderType type;
        private OrderStatus status;
        private Date creationTime;
        private Date executionTime;
        
        // 构造函数、getter和setter方法省略
        
        @Override
        public String toString() {
            return "Order{" +
                "orderId='" + orderId + '\'' +
                ", symbol='" + symbol + '\'' +
                ", price=" + price +
                ", quantity=" + quantity +
                ", type=" + type +
                ", status=" + status +
                '}';
        }
    }
    
    /**
     * 订单类型枚举
     */
    public enum OrderType {
        BUY, SELL
    }
    
    /**
     * 订单状态枚举
     */
    public enum OrderStatus {
        PENDING, EXECUTED, CANCELLED
    }
}

结语

本文展示了多种编程语言的代码示例,并且每个代码块都支持语法高亮和一键复制功能。这些特性可以帮助读者更轻松地阅读和使用代码。

要在自己的文章中使用代码高亮,只需要像下面这样使用Markdown代码块语法:

```javascript
// 你的JavaScript代码
console.log("Hello World!");
```

其中 javascript 是指定的语言,支持多种常见编程语言,如 Python、Java、C++、HTML、CSS、SQL 等。