Skip to content

Examples

Igor Sazonov edited this page Apr 5, 2026 · 1 revision

Real-world code you can copy, paste, and profit from. 💰


📈 Trading Bot Examples

Simple DCA Bot

Dollar-cost averaging made easy. Buy a fixed amount every day, regardless of price.

<?php

use Bingx;

class DcaBot
{
    private string $symbol = 'BTC-USDT';
    private float $dailyAmount = 100.0;  // $100 per day
    private int $leverage = 1;
    
    public function run(): void
    {
        while (true) {
            try {
                $this->executeDailyBuy();
                $this->logStatus();
                
                // Wait 24 hours
                sleep(86400);
                
            } catch (\Exception $e) {
                $this->alert("DCA failed: {$e->getMessage()}");
                sleep(3600);  // Retry in 1 hour
            }
        }
    }
    
    private function executeDailyBuy(): void
    {
        $order = Bingx::trade()->order()
            ->futures()
            ->symbol($this->symbol)
            ->buy()
            ->long()
            ->type('MARKET')
            ->margin($this->dailyAmount)
            ->leverage($this->leverage)
            ->execute();
            
        $this->log("Bought: Order #{$order['orderId']}");
    }
    
    private function logStatus(): void
    {
        $position = Bingx::account()->getPositions($this->symbol);
        $balance = Bingx::account()->getBalance();
        
        $this->log("Position: {$position[0]['positionAmt'] ?? 0} BTC");
        $this->log("Balance: {$balance['balance']['availableMargin']}");
    }
    
    private function log(string $message): void
    {
        echo "[" . date('Y-m-d H:i:s') . "] {$message}\n";
    }
    
    private function alert(string $message): void
    {
        // Send to Telegram, Discord, email, etc.
        $this->log("⚠️ ALERT: {$message}");
    }
}

// Run it
$bot = new DcaBot();
$bot->run();

Grid Trading Bot

Buy low, sell high, automatically. Perfect for ranging markets.

<?php

use Bingx;

class GridBot
{
    private string $symbol = 'BTC-USDT';
    private float $lowerPrice = 45000;
    private float $upperPrice = 55000;
    private int $gridLevels = 10;
    private float $amountPerGrid = 50;  // $50 per grid
    
    private array $gridOrders = [];
    
    public function setup(): void
    {
        $priceStep = ($this->upperPrice - $this->lowerPrice) / $this->gridLevels;
        
        for ($i = 0; $i <= $this->gridLevels; $i++) {
            $price = $this->lowerPrice + ($priceStep * $i);
            $this->gridOrders[$i] = [
                'price' => $price,
                'orderId' => null,
                'side' => null
            ];
        }
        
        $this->placeInitialOrders();
    }
    
    private function placeInitialOrders(): void
    {
        $currentPrice = Bingx::market()->getLatestPrice($this->symbol)['price'];
        
        foreach ($this->gridOrders as $i => &$grid) {
            if ($grid['price'] < $currentPrice) {
                // Place buy order below current price
                $order = $this->placeLimitOrder('BUY', $grid['price']);
                $grid['orderId'] = $order['orderId'];
                $grid['side'] = 'BUY';
            } else {
                // Place sell order above current price
                $order = $this->placeLimitOrder('SELL', $grid['price']);
                $grid['orderId'] = $order['orderId'];
                $grid['side'] = 'SELL';
            }
        }
        
        echo "Grid setup complete: {$this->gridLevels} levels\n";
    }
    
    private function placeLimitOrder(string $side, float $price): array
    {
        $builder = Bingx::trade()->order()
            ->futures()
            ->symbol($this->symbol)
            ->type('LIMIT')
            ->price($price)
            ->margin($this->amountPerGrid)
            ->leverage(5);
            
        if ($side === 'BUY') {
            $builder->buy()->long();
        } else {
            $builder->sell()->long();
        }
        
        return $builder->execute();
    }
    
    public function monitor(): void
    {
        while (true) {
            $this->checkFilledOrders();
            sleep(10);  // Check every 10 seconds
        }
    }
    
    private function checkFilledOrders(): void
    {
        foreach ($this->gridOrders as $i => &$grid) {
            if (!$grid['orderId']) continue;
            
            $order = Bingx::trade()->getOrder($this->symbol, $grid['orderId']);
            
            if ($order['status'] === 'FILLED') {
                echo "Grid {$i} filled at {$grid['price']}\n";
                
                // Place opposite order
                $newSide = $grid['side'] === 'BUY' ? 'SELL' : 'BUY';
                $newOrder = $this->placeLimitOrder($newSide, $grid['price']);
                
                $grid['orderId'] = $newOrder['orderId'];
                $grid['side'] = $newSide;
            }
        }
    }
}

$grid = new GridBot();
$grid->setup();
$grid->monitor();

Trailing Stop Manager

Automatically add trailing stops to all your positions.

<?php

use Bingx;

class TrailingStopManager
{
    private float $callbackRate = 2.0;  // 2% trailing distance
    private array $managedPositions = [];
    
    public function run(): void
    {
        while (true) {
            $positions = Bingx::account()->getPositions();
            
            foreach ($positions as $pos) {
                if (empty($pos['positionAmt'])) continue;
                
                $symbol = $pos['symbol'];
                $side = $pos['positionSide'];
                
                if (!isset($this->managedPositions["{$symbol}_{$side}"])) {
                    $this->addTrailingStop($pos);
                }
            }
            
            sleep(60);  // Check every minute
        }
    }
    
    private function addTrailingStop(array $position): void
    {
        $symbol = $position['symbol'];
        $side = $position['positionSide'];
        $entryPrice = (float) $position['entryPrice'];
        $quantity = abs((float) $position['positionAmt']);
        
        // Calculate activation price (2% in profit)
        $activationPrice = $side === 'LONG' 
            ? $entryPrice * 1.02 
            : $entryPrice * 0.98;
        
        $order = Bingx::trade()->order()
            ->futures()
            ->symbol($symbol)
            ->type('TRAILING_STOP_MARKET')
            ->activationPrice($activationPrice)
            ->callbackRate($this->callbackRate)
            ->quantity($quantity);
            
        if ($side === 'LONG') {
            $order->sell()->long();
        } else {
            $order->buy()->short();
        }
        
        $result = $order->execute();
        
        $this->managedPositions["{$symbol}_{$side}"] = $result['orderId'];
        echo "Added trailing stop for {$symbol} {$side}\n";
    }
}

$manager = new TrailingStopManager();
$manager->run();

📊 Analytics Examples

P&L Dashboard

Track your trading performance.

<?php

use Bingx;

class PnLDashboard
{
    public function getDailyStats(string $symbol = null): array
    {
        $startTime = strtotime('today midnight') * 1000;
        
        $income = Bingx::account()->getIncomeHistory(
            symbol: $symbol,
            startTime: $startTime,
            limit: 1000
        );
        
        $stats = [
            'realized_pnl' => 0,
            'funding_fees' => 0,
            'commissions' => 0,
            'trades' => 0
        ];
        
        foreach ($income as $item) {
            switch ($item['incomeType']) {
                case 'REALIZED_PNL':
                    $stats['realized_pnl'] += (float) $item['income'];
                    $stats['trades']++;
                    break;
                case 'FUNDING_FEE':
                    $stats['funding_fees'] += (float) $item['income'];
                    break;
                case 'COMMISSION':
                    $stats['commissions'] += (float) $item['income'];
                    break;
            }
        }
        
        $stats['net_pnl'] = $stats['realized_pnl'] + $stats['funding_fees'] + $stats['commissions'];
        
        return $stats;
    }
    
    public function getPositionSummary(): array
    {
        $positions = Bingx::account()->getPositions();
        $summary = [];
        
        foreach ($positions as $pos) {
            if (empty($pos['positionAmt'])) continue;
            
            $risk = Bingx::account()->getPositionRisk($pos['symbol']);
            
            $summary[] = [
                'symbol' => $pos['symbol'],
                'side' => $pos['positionSide'],
                'size' => $pos['positionAmt'],
                'entry' => $pos['entryPrice'],
                'pnl' => $pos['unrealizedProfit'],
                'pnl_percent' => $this->calculatePnLPercent($pos),
                'margin_ratio' => $risk['marginRatio'] ?? 0,
                'liquidation' => $risk['liquidationPrice'] ?? 0
            ];
        }
        
        return $summary;
    }
    
    private function calculatePnLPercent(array $position): float
    {
        $entry = (float) $position['entryPrice'];
        $pnl = (float) $position['unrealizedProfit'];
        $margin = (float) $position['positionInitialMargin'];
        
        if ($margin == 0) return 0;
        
        return round(($pnl / $margin) * 100, 2);
    }
    
    public function display(): void
    {
        echo "=== P&L Dashboard ===\n\n";
        
        // Daily stats
        $daily = $this->getDailyStats();
        echo "Today's Performance:\n";
        echo "  Realized P&L: \${$daily['realized_pnl']}\n";
        echo "  Funding Fees: \${$daily['funding_fees']}\n";
        echo "  Commissions: \${$daily['commissions']}\n";
        echo "  Net P&L: \${$daily['net_pnl']}\n";
        echo "  Trades: {$daily['trades']}\n\n";
        
        // Positions
        $positions = $this->getPositionSummary();
        echo "Open Positions:\n";
        foreach ($positions as $pos) {
            $emoji = $pos['pnl'] >= 0 ? '🟢' : '🔴';
            echo "  {$emoji} {$pos['symbol']} {$pos['side']}: ";
            echo "\${$pos['pnl']} ({$pos['pnl_percent']}%)\n";
        }
    }
}

$dashboard = new PnLDashboard();
$dashboard->display();

Market Scanner

Find trading opportunities across multiple pairs.

<?php

use Bingx;

class MarketScanner
{
    private array $watchlist = [
        'BTC-USDT', 'ETH-USDT', 'SOL-USDT', 'BNB-USDT',
        'XRP-USDT', 'ADA-USDT', 'DOGE-USDT', 'AVAX-USDT'
    ];
    
    public function scan(): array
    {
        $opportunities = [];
        
        foreach ($this->watchlist as $symbol) {
            $analysis = $this->analyzeSymbol($symbol);
            
            if ($analysis['signal'] !== 'NEUTRAL') {
                $opportunities[] = $analysis;
            }
        }
        
        // Sort by strength
        usort($opportunities, fn($a, $b) => $b['strength'] <=> $a['strength']);
        
        return $opportunities;
    }
    
    private function analyzeSymbol(string $symbol): array
    {
        // Get data
        $klines = Bingx::market()->getKlines($symbol, '1h', 24);
        $ticker = Bingx::market()->get24hrTicker($symbol);
        $funding = Bingx::market()->getFundingRateInfo($symbol);
        $oi = Bingx::market()->getOpenInterest($symbol);
        
        // Calculate metrics
        $priceChange = (float) $ticker['priceChangePercent'];
        $volume = (float) $ticker['volume'];
        $fundingRate = (float) ($funding['fundingRate'] ?? 0);
        
        // Simple signal logic
        $signal = 'NEUTRAL';
        $strength = 0;
        
        if ($priceChange > 3 && $fundingRate < 0.01) {
            $signal = 'LONG';
            $strength = min(abs($priceChange), 10);
        } elseif ($priceChange < -3 && $fundingRate > -0.01) {
            $signal = 'SHORT';
            $strength = min(abs($priceChange), 10);
        }
        
        return [
            'symbol' => $symbol,
            'price' => $ticker['lastPrice'],
            'change_24h' => $priceChange,
            'volume_24h' => $volume,
            'funding_rate' => $fundingRate,
            'open_interest' => $oi['openInterest'] ?? 0,
            'signal' => $signal,
            'strength' => $strength
        ];
    }
    
    public function display(): void
    {
        $opportunities = $this->scan();
        
        echo "=== Market Scanner ===\n\n";
        
        if (empty($opportunities)) {
            echo "No strong signals found.\n";
            return;
        }
        
        foreach ($opportunities as $opp) {
            $emoji = $opp['signal'] === 'LONG' ? '🟢' : '🔴';
            echo "{$emoji} {$opp['symbol']}: {$opp['signal']}\n";
            echo "   Price: {$opp['price']} ({$opp['change_24h']}%)\n";
            echo "   Funding: {$opp['funding_rate']}\n";
            echo "   Strength: {$opp['strength']}/10\n\n";
        }
    }
}

$scanner = new MarketScanner();
$scanner->display();

🛡️ Risk Management Examples

Position Size Calculator

Never risk more than you can afford to lose.

<?php

use Bingx;

class PositionCalculator
{
    public function calculate(
        string $symbol,
        float $riskPercent,
        float $stopLossPercent,
        int $leverage
    ): array {
        $balance = Bingx::account()->getBalance();
        $availableMargin = (float) $balance['balance']['availableMargin'];
        
        $price = Bingx::market()->getLatestPrice($symbol)['price'];
        
        // Risk amount
        $riskAmount = $availableMargin * ($riskPercent / 100);
        
        // Position size based on stop loss
        $stopLossDistance = $stopLossPercent / 100;
        $positionValue = $riskAmount / $stopLossDistance;
        
        // Margin needed
        $marginNeeded = $positionValue / $leverage;
        
        // Quantity
        $quantity = $positionValue / $price;
        
        return [
            'symbol' => $symbol,
            'current_price' => $price,
            'available_margin' => $availableMargin,
            'risk_amount' => round($riskAmount, 2),
            'position_value' => round($positionValue, 2),
            'margin_needed' => round($marginNeeded, 2),
            'quantity' => round($quantity, 6),
            'stop_loss_price' => round($price * (1 - $stopLossDistance), 2),
            'leverage' => $leverage,
            'can_afford' => $marginNeeded <= $availableMargin
        ];
    }
    
    public function display(string $symbol): void
    {
        $calc = $this->calculate(
            symbol: $symbol,
            riskPercent: 2,      // Risk 2% of account
            stopLossPercent: 4,  // 4% stop loss
            leverage: 10
        );
        
        echo "=== Position Calculator ===\n\n";
        echo "Symbol: {$calc['symbol']}\n";
        echo "Price: \${$calc['current_price']}\n";
        echo "Available: \${$calc['available_margin']}\n\n";
        
        echo "Recommended Position:\n";
        echo "  Quantity: {$calc['quantity']}\n";
        echo "  Value: \${$calc['position_value']}\n";
        echo "  Margin: \${$calc['margin_needed']}\n";
        echo "  Stop Loss: \${$calc['stop_loss_price']}\n";
        echo "  Risk: \${$calc['risk_amount']} (2%)\n\n";
        
        $status = $calc['can_afford'] ? '✅ Affordable' : '❌ Insufficient margin';
        echo "Status: {$status}\n";
    }
}

$calc = new PositionCalculator();
$calc->display('BTC-USDT');

Risk Monitor

Watch all positions and alert when danger approaches.

<?php

use Bingx;

class RiskMonitor
{
    private float $warningThreshold = 70;
    private float $dangerThreshold = 85;
    private float $criticalThreshold = 95;
    
    public function monitor(): void
    {
        while (true) {
            $this->checkAllPositions();
            sleep(30);  // Check every 30 seconds
        }
    }
    
    private function checkAllPositions(): void
    {
        $positions = Bingx::account()->getPositions();
        
        foreach ($positions as $pos) {
            if (empty($pos['positionAmt'])) continue;
            
            $risk = Bingx::account()->getPositionRisk($pos['symbol']);
            $marginRatio = (float) ($risk['marginRatio'] ?? 0);
            
            $this->evaluateRisk($pos['symbol'], $pos['positionSide'], $marginRatio);
        }
    }
    
    private function evaluateRisk(string $symbol, string $side, float $marginRatio): void
    {
        if ($marginRatio >= $this->criticalThreshold) {
            $this->alert("🚨 CRITICAL: {$symbol} {$side} at {$marginRatio}%! LIQUIDATION IMMINENT!");
            $this->emergencyClose($symbol, $side);
            
        } elseif ($marginRatio >= $this->dangerThreshold) {
            $this->alert("⚠️ DANGER: {$symbol} {$side} at {$marginRatio}%! Add margin or reduce position!");
            
        } elseif ($marginRatio >= $this->warningThreshold) {
            $this->alert("⚡ WARNING: {$symbol} {$side} at {$marginRatio}%. Monitor closely.");
        }
    }
    
    private function emergencyClose(string $symbol, string $side): void
    {
        try {
            Bingx::trade()->closeAllPositions($symbol);
            $this->alert("✅ Emergency close executed for {$symbol}");
        } catch (\Exception $e) {
            $this->alert("❌ Emergency close FAILED: {$e->getMessage()}");
        }
    }
    
    private function alert(string $message): void
    {
        echo "[" . date('H:i:s') . "] {$message}\n";
        
        // Add your notification logic here:
        // - Telegram bot
        // - Discord webhook
        // - Email
        // - SMS
    }
}

$monitor = new RiskMonitor();
$monitor->monitor();

🔄 TWAP Examples

Large Position Builder

Accumulate a large position without moving the market.

<?php

use Bingx;

class PositionBuilder
{
    public function accumulate(
        string $symbol,
        float $totalQuantity,
        int $durationHours,
        ?float $maxPrice = null
    ): array {
        $durationSeconds = $durationHours * 3600;
        
        $twap = Bingx::twap()->buy(
            symbol: $symbol,
            quantity: $totalQuantity,
            duration: $durationSeconds,
            price: $maxPrice,
            positionSide: 'LONG'
        );
        
        echo "TWAP order created: {$twap['orderId']}\n";
        echo "Accumulating {$totalQuantity} {$symbol} over {$durationHours} hours\n";
        
        // Monitor progress
        return $this->monitorProgress($twap['orderId']);
    }
    
    private function monitorProgress(string $orderId): array
    {
        while (true) {
            $details = Bingx::twap()->getOrderDetail($orderId);
            
            $executed = (float) $details['executedQty'];
            $total = (float) $details['totalQty'];
            $progress = ($executed / $total) * 100;
            
            echo sprintf(
                "[%s] Progress: %.2f%% | Executed: %.4f | Avg Price: %s\n",
                date('H:i:s'),
                $progress,
                $executed,
                $details['avgPrice']
            );
            
            if (in_array($details['status'], ['FILLED', 'CANCELLED', 'EXPIRED'])) {
                echo "Order completed with status: {$details['status']}\n";
                return $details;
            }
            
            sleep(60);  // Update every minute
        }
    }
}

$builder = new PositionBuilder();
$result = $builder->accumulate(
    symbol: 'BTC-USDT',
    totalQuantity: 5.0,
    durationHours: 4,
    maxPrice: 52000.0  // Don't pay more than $52k
);

🌐 WebSocket Examples

Real-Time Price Monitor

<?php

use Tigusigalpa\BingX\Websocket\BingxWebsocket;

$ws = new BingxWebsocket();

// Subscribe to price updates
$ws->subscribe('BTC-USDT@trade', function($data) {
    $price = $data['p'];
    $quantity = $data['q'];
    $side = $data['m'] ? 'SELL' : 'BUY';
    
    echo "[{$side}] BTC: \${$price} x {$quantity}\n";
});

// Subscribe to kline updates
$ws->subscribe('BTC-USDT@kline_1m', function($data) {
    $kline = $data['k'];
    echo "1m Candle: O:{$kline['o']} H:{$kline['h']} L:{$kline['l']} C:{$kline['c']}\n";
});

$ws->run();

📱 Laravel Integration Examples

Trading Controller

<?php

namespace App\Http\Controllers;

use Bingx;
use Illuminate\Http\Request;

class TradingController extends Controller
{
    public function dashboard()
    {
        $balance = Bingx::account()->getBalance();
        $positions = Bingx::account()->getPositions();
        $orders = Bingx::trade()->getOpenOrders();
        
        return view('trading.dashboard', compact('balance', 'positions', 'orders'));
    }
    
    public function placeOrder(Request $request)
    {
        $validated = $request->validate([
            'symbol' => 'required|string',
            'side' => 'required|in:BUY,SELL',
            'type' => 'required|in:MARKET,LIMIT',
            'margin' => 'required|numeric|min:10',
            'leverage' => 'required|integer|min:1|max:125',
            'price' => 'nullable|numeric',
        ]);
        
        try {
            $builder = Bingx::trade()->order()
                ->futures()
                ->symbol($validated['symbol'])
                ->type($validated['type'])
                ->margin($validated['margin'])
                ->leverage($validated['leverage']);
                
            if ($validated['side'] === 'BUY') {
                $builder->buy()->long();
            } else {
                $builder->sell()->short();
            }
            
            if ($validated['type'] === 'LIMIT' && $validated['price']) {
                $builder->price($validated['price']);
            }
            
            $order = $builder->execute();
            
            return response()->json([
                'success' => true,
                'order' => $order
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 400);
        }
    }
    
    public function closePosition(Request $request, string $symbol)
    {
        try {
            Bingx::trade()->closeAllPositions($symbol);
            
            return response()->json(['success' => true]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 400);
        }
    }
}

Scheduled Risk Check (Laravel)

<?php

namespace App\Console\Commands;

use Bingx;
use Illuminate\Console\Command;
use App\Notifications\RiskAlert;

class CheckPositionRisk extends Command
{
    protected $signature = 'trading:check-risk';
    protected $description = 'Check position risk and send alerts';
    
    public function handle()
    {
        $positions = Bingx::account()->getPositions();
        
        foreach ($positions as $pos) {
            if (empty($pos['positionAmt'])) continue;
            
            $risk = Bingx::account()->getPositionRisk($pos['symbol']);
            $marginRatio = (float) ($risk['marginRatio'] ?? 0);
            
            if ($marginRatio > 80) {
                // Send notification
                $user = auth()->user();
                $user->notify(new RiskAlert($pos['symbol'], $marginRatio));
                
                $this->warn("High risk: {$pos['symbol']} at {$marginRatio}%");
            }
        }
        
        $this->info('Risk check completed.');
    }
}

Add to app/Console/Kernel.php:

$schedule->command('trading:check-risk')->everyMinute();

🎯 Quick Snippets

Get Current Price

$price = Bingx::market()->getLatestPrice('BTC-USDT')['price'];

Check Balance

$available = Bingx::account()->getBalance()['balance']['availableMargin'];

Market Buy

Bingx::trade()->order()
    ->futures()
    ->symbol('BTC-USDT')
    ->buy()->long()
    ->type('MARKET')
    ->margin(100)
    ->leverage(10)
    ->execute();

Set Stop Loss

Bingx::trade()->order()
    ->futures()
    ->symbol('BTC-USDT')
    ->sell()->long()
    ->type('STOP_MARKET')
    ->stopPrice(48000)
    ->closePosition(true)
    ->execute();

Close All Positions

Bingx::trade()->closeAllPositions('BTC-USDT');

Cancel All Orders

Bingx::trade()->cancelAllOrders('BTC-USDT');

Need more examples? Open an issue and tell us what you're building!

Clone this wiki locally