Ever cannonballed into a pool and splashed everyone? That's what a big market order does to the price. TWAP is like slowly walking in. The water barely notices. Your fills are better. Everyone's happy. ## Why Should You Care? Let me tell you a $5,000 story. **The Old Way (ouch):** - You want 10 BTC - You smash that market buy button - Price jumps from $50k to $51k as YOUR order moves the market - Average fill: $50.5k - You just paid $5,000 extra. To yourself. Against yourself. 🤦 **The TWAP Way (smart):** - You want 10 BTC over 1 hour - TWAP buys 0.1 BTC every 6 minutes - Market barely notices - Average fill: $50.05k - You saved $4,500. Buy yourself something nice. ## Let's Do This ### The Simple Way ```php $twap = Bingx::twap()->buy( symbol: 'BTC-USDT', quantity: 10.0, duration: 3600, // 1 hour in seconds positionSide: 'LONG' ); echo "TWAP Order Created: {$twap['orderId']}\n"; ``` ### Selling Works Too ```php $twap = Bingx::twap()->sell( symbol: 'ETH-USDT', quantity: 50.0, duration: 1800, // 30 minutes positionSide: 'SHORT' ); ``` ### Want a Price Limit? ```php // "I want 5 BTC, but only if I can get it under $50k" $twap = Bingx::twap()->buy( symbol: 'BTC-USDT', quantity: 5.0, duration: 7200, // 2 hours price: 50000.0, // Limit price positionSide: 'LONG' ); ``` ## Getting Fancy ### Full Control Mode ```php $twap = Bingx::twap()->createOrder([ 'symbol' => 'BTC-USDT', 'side' => 'BUY', 'positionSide' => 'LONG', 'quantity' => 10.0, 'duration' => 3600, 'price' => 49500.0, // Optional limit price 'clientOrderId' => 'my-twap-' . time() // Custom ID for tracking ]); ``` ### Watch It Work ```php // Check how your TWAP is doing $details = Bingx::twap()->getOrderDetail($orderId); echo "Status: {$details['status']}\n"; echo "Progress: {$details['executedQty']}/{$details['totalQty']}\n"; echo "Avg Price: {$details['avgPrice']}\n"; echo "Time Remaining: {$details['remainingTime']}s\n"; // Calculate completion percentage $progress = ($details['executedQty'] / $details['totalQty']) * 100; echo "Completion: {$progress}%\n"; ``` ### What's Currently Running? ```php // See all your active TWAP orders $openOrders = Bingx::twap()->getOpenOrders(); // For specific symbol $btcOrders = Bingx::twap()->getOpenOrders('BTC-USDT'); foreach ($btcOrders as $order) { echo "Order {$order['orderId']}: "; echo "{$order['executedQty']}/{$order['quantity']} @ {$order['avgPrice']}\n"; } ``` ### Get TWAP History ```php $history = Bingx::twap()->getHistoryOrders( symbol: 'BTC-USDT', limit: 50, startTime: strtotime('-7 days') * 1000, endTime: time() * 1000 ); foreach ($history as $order) { echo "{$order['createTime']}: {$order['side']} {$order['quantity']} "; echo "@ {$order['avgPrice']} - {$order['status']}\n"; } ``` ### Get All Orders (Open + History) ```php $allOrders = Bingx::twap()->getAllOrders( symbol: 'BTC-USDT', limit: 100 ); ``` ### Changed Your Mind? ```php // Pull the plug on a TWAP order $result = Bingx::twap()->cancelOrder($orderId, 'BTC-USDT'); if ($result['code'] === 0) { echo "Order cancelled successfully\n"; } ``` ## Real Stories From Real Trading ### The Whale Accumulation Play ```php // Accumulate 100 BTC over 24 hours // This is $5M at $50k - you don't want to do this all at once! $twap = Bingx::twap()->buy( symbol: 'BTC-USDT', quantity: 100.0, duration: 86400, // 24 hours positionSide: 'LONG' ); // Check progress every hour for ($i = 0; $i < 24; $i++) { sleep(3600); // Wait 1 hour $details = Bingx::twap()->getOrderDetail($twap['orderId']); $progress = ($details['executedQty'] / $details['totalQty']) * 100; echo "Hour {$i}: {$progress}% complete, avg price {$details['avgPrice']}\n"; } ``` ### The "Oh Crap, Get Me Out" Exit ```php // You're long 50 BTC. Market's turning. Time to leave. // But do it gracefully, not desperately. $twap = Bingx::twap()->sell( symbol: 'BTC-USDT', quantity: 50.0, duration: 7200, // 2 hours positionSide: 'LONG' // Closing long ); // Monitor and cancel if price drops too fast while (true) { $details = Bingx::twap()->getOrderDetail($twap['orderId']); if ($details['status'] === 'FILLED') { echo "Position fully closed at avg {$details['avgPrice']}\n"; break; } // Check current price $currentPrice = Bingx::market()->getLatestPrice('BTC-USDT'); // If price drops 5% below our average, cancel TWAP and market sell if ($currentPrice['price'] < $details['avgPrice'] * 0.95) { Bingx::twap()->cancelOrder($twap['orderId'], 'BTC-USDT'); // Market sell remaining $remaining = $details['totalQty'] - $details['executedQty']; Bingx::trade()->order() ->futures() ->symbol('BTC-USDT') ->sell() ->long() ->type('MARKET') ->quantity($remaining) ->execute(); echo "Emergency exit triggered\n"; break; } sleep(60); // Check every minute } ``` ### The Patient Accumulator ```php // DCA on autopilot: $10k of BTC every day for a month for ($day = 1; $day <= 30; $day++) { // Get current price $price = Bingx::market()->getLatestPrice('BTC-USDT'); $quantity = 10000 / $price['price']; // $10k worth // Execute over 23 hours (leave 1 hour gap) $twap = Bingx::twap()->buy( symbol: 'BTC-USDT', quantity: $quantity, duration: 82800, // 23 hours positionSide: 'LONG' ); echo "Day {$day}: Buying {$quantity} BTC\n"; // Wait for next day sleep(86400); } ``` ## The Wisdom Section ### How Long Should Your TWAP Run? - **Minimum:** 10 minutes (any shorter and why bother?) - **Sweet spot:** 30-60 minutes for most trades - **Maximum:** 24 hours (for the really big moves) **The rule:** Bigger order = longer duration. Simple. ```php // If your order is 1% of daily volume → 30-60 minutes // If your order is 5% of daily volume → 2-4 hours // If your order is 10%+ of daily volume → 6-12 hours ``` ### When TWAP Makes Sense **Use it when:** - Your order is big enough to move the market - You're not in a rush - You want better average prices - You're accumulating or distributing quietly **Skip it when:** - Small orders (just market buy, it's fine) - You need in/out RIGHT NOW - The market is running away from you (chase it manually) ### To Limit or Not to Limit? ```php // "Just get me in, I don't care about the exact price" $twap = Bingx::twap()->buy( symbol: 'BTC-USDT', quantity: 10.0, duration: 3600, price: null, // Market price, whatever it is positionSide: 'LONG' ); // "I want in, but I'm not paying more than $49k" $twap = Bingx::twap()->buy( symbol: 'BTC-USDT', quantity: 10.0, duration: 3600, price: 49000.0, // My line in the sand positionSide: 'LONG' ); ``` **Use limits when:** You have a price you won't cross. Period. **Use market when:** Getting the position matters more than the exact price. ### Monitoring Always monitor your TWAP orders: ```php function monitorTwap($orderId, $symbol) { while (true) { $details = Bingx::twap()->getOrderDetail($orderId); if ($details['status'] === 'FILLED') { return $details; } if ($details['status'] === 'CANCELLED' || $details['status'] === 'EXPIRED') { throw new Exception("TWAP order {$details['status']}"); } $progress = ($details['executedQty'] / $details['totalQty']) * 100; echo date('H:i:s') . " - Progress: {$progress}%, Avg: {$details['avgPrice']}\n"; sleep(60); // Check every minute } } $twap = Bingx::twap()->buy('BTC-USDT', 10.0, 3600, 'LONG'); $result = monitorTwap($twap['orderId'], 'BTC-USDT'); echo "Completed! Avg price: {$result['avgPrice']}\n"; ``` ## What Do These Statuses Mean? - `NEW` — Just created, hasn't started buying/selling yet - `PARTIALLY_FILLED` — Working on it... patience - `FILLED` — Done! Check your average price. - `CANCELLED` — You pulled the plug - `EXPIRED` — Time ran out before it finished (you got partial fills) - `REJECTED` — Something went wrong (check the error) ## Limitations - **Minimum duration:** 600 seconds (10 minutes) - **Maximum duration:** 86400 seconds (24 hours) - **Minimum quantity:** Depends on symbol (usually 0.001 BTC) - **Maximum open orders:** Check with `Bingx::trade()->getMaxOpenOrders()` ## Error Handling ```php try { $twap = Bingx::twap()->buy( symbol: 'BTC-USDT', quantity: 10.0, duration: 3600, positionSide: 'LONG' ); } catch (\Tigusigalpa\BingX\Exceptions\InsufficientBalanceException $e) { echo "Not enough balance: {$e->getMessage()}\n"; } catch (\Tigusigalpa\BingX\Exceptions\ApiException $e) { echo "API error: {$e->getMessage()}\n"; echo "Code: {$e->getCode()}\n"; } ``` ## Questions You're Probably Asking **"Can I change a TWAP order after I create it?"** Nope. Cancel it and make a new one. Sorry. **"What if it doesn't finish in time?"** You keep whatever got filled. The rest just... doesn't happen. **"Can I TWAP on spot?"** Not yet. Futures only for now. **"Will TWAP always get me better prices?"** Usually, yes. Guaranteed? No. Markets are weird sometimes. **"Can I run multiple TWAPs at once?"** Yes! Just don't forget about them. And watch your margin. --- **Ready for more?** Check out [Advanced Order Types](Advanced-Order-Types.md) — trailing stops, trigger limits, and other cool stuff.