Leverage trading on Flash.Trade with position management
const position = await agent.methods.flashOpenTrade({ token: "SOL", // Token to trade side: "long", // Position side collateralUsd: 1000, // Collateral in USD leverage: 5 // Leverage multiplier });
const closure = await agent.methods.flashCloseTrade({ token: "SOL", // Token to close side: "long" // Position side });
const MARKET_TOKENS = { SOL: { long: { marketID: "..." }, short: { marketID: "..." } }, BTC: { long: { marketID: "..." }, short: { marketID: "..." } }, ETH: { long: { marketID: "..." }, short: { marketID: "..." } } };
"Open a 5x leveraged long SOL position with 1000 USD" "Close my ETH short position" "Create a 10x BTC long with 500 USD collateral" "Exit my SOL long position"
{ "token": "SOL", "type": "long", "collateral": 1000, "leverage": 5 }
{ "token": "SOL", "side": "long" }
interface FlashTradeParams { token: string; // Token symbol side: "long" | "short"; // Position side collateralUsd: number; // Collateral amount leverage: number; // Leverage multiplier } // Calculate position size const positionSize = perpClient.getSizeAmountFromLeverageAndCollateral( collateralAmount, leverage, targetToken, collateralToken, side, targetPrice, collateralPrice, targetCustody, collateralCustody );
interface FlashCloseTradeParams { token: string; // Token symbol side: "long" | "short"; // Position side } // Calculate exit price with slippage const priceWithSlippage = perpClient.getPriceAfterSlippage( false, // isEntry new BN(100), // 1% slippage targetPrice.price, side );
// Opening positions const OPEN_POSITION_CU = 400000; // Closing positions const CLOSE_POSITION_CU = 300000; const computeBudgetIx = ComputeBudgetProgram.setComputeUnitLimit({ units: OPEN_POSITION_CU // or CLOSE_POSITION_CU });
try { const tx = await agent.methods.flashOpenTrade(params); } catch (error) { if (error.message.includes("Token not supported")) { // Handle unsupported token } else if (error.message.includes("slippage")) { // Handle excessive slippage } }
function convertPriceToNumber(oraclePrice: OraclePrice): number { const price = parseInt(oraclePrice.price.toString("hex"), 16); const exponent = parseInt(oraclePrice.exponent.toString("hex"), 16); return price * Math.pow(10, exponent); }
function calculateCollateralAmount( usdAmount: number, tokenPrice: number, decimals: number ): BN { return new BN((usdAmount / tokenPrice) * Math.pow(10, decimals)); }
const marketSdkInfo = { [marketId]: { tokenPair: string; // e.g., "SOL/USD" pool: string; // Pool identifier // Additional market data } };
Was this page helpful?