Cookbook
Trailing stop and break-even.
A position whose stop loss trails the price by 0.5% and moves to break-even once the price has gone 0.5% your way, all on the API's servers.
The whole program, in each language. Set PHOENIXPERPS_API_KEY to a sandbox key (ppk_test_...) and run it. Follows the account stream for 30 s to watch the stop move, then closes.
import { once } from 'node:events';
import { PhoenixPerps } from '@phoenixperps/sdk';
const client = new PhoenixPerps();
if (client.environment === 'live' && process.env.PHOENIXPERPS_ALLOW_LIVE !== 'yes') {
console.error('This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).');
process.exit(1);
}
const [account] = (await client.accounts.list()).data;
const btc = await client.markets.get('BTC-USD');
// the stream first, so every event of the stop is told, from its placing on
const stream = client.accountStream({ accounts: [account.id] });
stream.on('event', (e) => {
if (e.type.startsWith('strategy.')) console.log(`${new Date(e.time).toISOString()} ${e.type} ${JSON.stringify(e.data)}`);
});
stream.start();
await once(stream, 'ready');
const order = await client.orders.create(account.id, {
market: 'BTC-USD',
side: 'buy',
type: 'market',
size: btc.min_size,
exits: {
stop_loss: {
percent: '1',
trail: { percent: '0.5' },
break_even: { trigger_percent: '0.5', offset_ticks: 2 },
},
},
});
console.log(`bought ${order.size} BTC at ${order.average_fill_price ?? '-'}; watching the stop for 30 s`);
await new Promise((r) => setTimeout(r, 30_000));
stream.close();
const close = await client.positions.close(account.id, 'BTC-USD', {});
console.log(`closed: ${close.status}`);import asyncio
import json
import os
from phoenixperps import PhoenixPerps
client = PhoenixPerps()
if client.environment == "live" and os.environ.get("PHOENIXPERPS_ALLOW_LIVE") != "yes":
raise SystemExit("This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).")
account = client.accounts.list().data[0]
btc = client.markets.get("BTC-USD")
async def main() -> None:
# the stream first, so every event of the stop is told, from its placing on
async with client.account_stream(accounts=[account["id"]]) as stream:
await stream.ready.wait()
order = client.orders.create(account["id"], {
"market": "BTC-USD",
"side": "buy",
"type": "market",
"size": btc["min_size"],
"exits": {
"stop_loss": {
"percent": "1",
"trail": {"percent": "0.5"},
"break_even": {"trigger_percent": "0.5", "offset_ticks": 2},
},
},
})
print(f'bought {order["size"]} BTC at {order.get("average_fill_price") or "-"}; watching the stop for 30 s')
async def watch() -> None:
async for event in stream:
if event["type"].startswith("strategy."):
print(f'{event["time"]} {event["type"]} {json.dumps(event["data"])}')
try:
await asyncio.wait_for(watch(), timeout=30)
except asyncio.TimeoutError:
pass
asyncio.run(main())
close = client.positions.close(account["id"], "BTC-USD", {})
print(f'closed: {close["status"]}')package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strings"
"time"
phoenixperps "github.com/phoenixperps/sdk/go"
)
func main() {
ctx := context.Background()
client, err := phoenixperps.NewClient()
if err != nil {
log.Fatal(err)
}
if client.Environment() == "live" && os.Getenv("PHOENIXPERPS_ALLOW_LIVE") != "yes" {
log.Fatal("This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).")
}
accounts, err := client.Accounts.List(ctx)
if err != nil {
log.Fatal(err)
}
account := accounts.Data[0].ID
btc, err := client.Markets.Get(ctx, "BTC-USD")
if err != nil {
log.Fatal(err)
}
// the stream first, so every event of the stop is told, from its placing on
watch, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
stream := client.AccountStream(watch, phoenixperps.AccountStreamOptions{Accounts: []string{account}})
<-stream.Ready()
order, err := client.Orders.Create(ctx, account, phoenixperps.CreateOrder{
Market: "BTC-USD",
Side: phoenixperps.OrderSideBuy,
Type: phoenixperps.CreateOrderTypeMarket,
Size: &btc.MinSize,
Exits: &phoenixperps.OrderExits{StopLoss: &phoenixperps.OrderExitsStopLoss{
Percent: phoenixperps.Dec("1"),
Trail: &phoenixperps.OrderExitsStopLossTrail{Percent: phoenixperps.Dec("0.5")},
BreakEven: &phoenixperps.OrderExitsStopLossBreakEven{TriggerPercent: phoenixperps.Dec("0.5"), OffsetTicks: phoenixperps.Ptr[int64](2)},
}},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("bought %s BTC (%s); watching the stop for 30 s\n", btc.MinSize, order.Status)
for {
e, err := stream.Next(watch)
if errors.Is(err, context.DeadlineExceeded) {
break
}
if err != nil {
log.Fatal(err)
}
if strings.HasPrefix(string(e.Type), "strategy.") {
b, _ := json.Marshal(e.Data)
fmt.Printf("%s %s %s\n", time.UnixMilli(e.Time).Format(time.RFC3339), e.Type, b)
}
}
_ = stream.Close()
closed, err := client.Positions.Close(ctx, account, "BTC-USD", phoenixperps.ClosePosition{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("closed: %s\n", closed.Status)
}#:package PhoenixPerps.Sdk@1.0.0
using System.Globalization;
using PhoenixPerps;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // decimals print as 0.0001 on every machine
using var client = new PhoenixPerpsClient();
if (client.Environment == "live" && Environment.GetEnvironmentVariable("PHOENIXPERPS_ALLOW_LIVE") != "yes")
{
Console.Error.WriteLine("This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).");
return 1;
}
var account = (await client.Accounts.ListAsync()).Data[0].Id;
var btc = await client.Markets.GetAsync("BTC-USD");
using var watch = new CancellationTokenSource(TimeSpan.FromSeconds(30));
// the stream first, so every event of the stop is told, from its placing on
await using (var stream = client.OpenAccountStream(new AccountStreamOptions { Accounts = new[] { account } }))
{
await stream.Ready;
var order = await client.Orders.CreateAsync(account, new CreateOrder
{
Market = "BTC-USD",
Side = OrderSide.Buy,
Type = CreateOrderType.Market,
Size = btc.MinSize,
Exits = new OrderExits
{
StopLoss = new OrderExitsStopLoss
{
Percent = 1m,
Trail = new() { Percent = 0.5m },
BreakEven = new() { TriggerPercent = 0.5m, OffsetTicks = 2 },
},
},
});
Console.WriteLine($"bought {order.Size} BTC ({order.Status}); watching the stop for 30 s");
try
{
await foreach (var e in stream.ReadAllAsync(watch.Token))
if (e.Type.ToString().StartsWith("strategy.", StringComparison.Ordinal))
Console.WriteLine($"{DateTimeOffset.FromUnixTimeMilliseconds(e.Time):O} {e.Type} {string.Join(" ", e.Data.Select(kv => $"{kv.Key}={kv.Value.GetRawText()}"))}");
}
catch (OperationCanceledException)
{
}
}
var closed = await client.Positions.CloseAsync(account, "BTC-USD", new ClosePosition());
Console.WriteLine($"closed: {closed.Status}");
return 0;import com.phoenixperpsfunding.sdk.AccountStream;
import com.phoenixperpsfunding.sdk.PhoenixPerpsClient;
import com.phoenixperpsfunding.sdk.gen.ClosePosition;
import com.phoenixperpsfunding.sdk.gen.CreateOrder;
import com.phoenixperpsfunding.sdk.gen.CreateOrderType;
import com.phoenixperpsfunding.sdk.gen.Event;
import com.phoenixperpsfunding.sdk.gen.Market;
import com.phoenixperpsfunding.sdk.gen.Order;
import com.phoenixperpsfunding.sdk.gen.OrderExits;
import com.phoenixperpsfunding.sdk.gen.OrderExitsStopLoss;
import com.phoenixperpsfunding.sdk.gen.OrderExitsStopLossBreakEven;
import com.phoenixperpsfunding.sdk.gen.OrderExitsStopLossTrail;
import com.phoenixperpsfunding.sdk.gen.OrderSide;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
final class Example06 {
public static void main(String[] args) throws InterruptedException {
PhoenixPerpsClient client = PhoenixPerpsClient.fromEnv();
if ("live".equals(client.environment()) && !"yes".equals(System.getenv("PHOENIXPERPS_ALLOW_LIVE"))) {
System.err.println("This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).");
System.exit(1);
}
String account = client.accounts().list().data().get(0).id();
Market btc = client.markets().get("BTC-USD");
Instant end = Instant.now().plusSeconds(30);
// the stream first, so every event of the stop is told, from its placing on
try (AccountStream stream = client.openAccountStream(AccountStream.options().accounts(List.of(account)))) {
stream.ready().join();
Order order = client.orders().create(account, new CreateOrder()
.market("BTC-USD")
.side(OrderSide.BUY)
.type(CreateOrderType.MARKET)
.size(btc.minSize())
.exits(new OrderExits().stopLoss(new OrderExitsStopLoss()
.percent(new BigDecimal("1"))
.trail(new OrderExitsStopLossTrail().percent(new BigDecimal("0.5")))
.breakEven(new OrderExitsStopLossBreakEven().triggerPercent(new BigDecimal("0.5")).offsetTicks(2L)))));
System.out.printf("bought %s BTC (%s); watching the stop for 30 s%n", order.size(), order.status());
while (Instant.now().isBefore(end)) {
Event e = stream.poll(Duration.between(Instant.now(), end));
if (e != null && e.type().toString().startsWith("strategy.")) {
System.out.printf("%s %s %s%n", Instant.ofEpochMilli(e.time()), e.type(), e.data());
}
}
}
Order closed = client.positions().close(account, "BTC-USD", new ClosePosition());
System.out.printf("closed: %s%n", closed.status());
}
}use std::time::Duration;
use phoenixperps::{
dec, AccountStreamOptions, Client, ClosePosition, CreateOrder, CreateOrderType, OrderExits, OrderExitsStopLoss, OrderExitsStopLossBreakEven,
OrderExitsStopLossTrail, OrderSide,
};
#[tokio::main]
async fn main() -> phoenixperps::Result<()> {
let client = Client::from_env()?;
if client.environment() == "live" && std::env::var("PHOENIXPERPS_ALLOW_LIVE").as_deref() != Ok("yes") {
eprintln!("This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).");
std::process::exit(1);
}
let account = client.accounts().list().await?.data[0].id.clone();
let btc = client.markets().get("BTC-USD").await?;
// the stream first, so every event of the stop is told, from its placing on
let mut stream = client.account_stream(AccountStreamOptions { accounts: vec![account.clone()], ..Default::default() });
stream.ready().await;
let trail = OrderExitsStopLossTrail { percent: Some(dec("0.5")), ..Default::default() };
let break_even = OrderExitsStopLossBreakEven { trigger_percent: Some(dec("0.5")), offset_ticks: Some(2), ..Default::default() };
let order = client
.orders()
.create(&account, &CreateOrder {
market: "BTC-USD".into(),
side: OrderSide::Buy,
r#type: CreateOrderType::Market,
size: Some(btc.min_size),
exits: Some(OrderExits {
stop_loss: Some(OrderExitsStopLoss { percent: Some(dec("1")), trail: Some(trail), break_even: Some(break_even), ..Default::default() }),
..Default::default()
}),
..Default::default()
})
.await?;
println!("bought BTC ({}); watching the stop for 30 s", order.status);
let watch = async {
while let Some(event) = stream.next().await {
let event = event?;
if event.r#type.to_string().starts_with("strategy.") {
println!("{} {} {:?}", event.time, event.r#type, event.data);
}
}
Ok::<(), phoenixperps::Error>(())
};
if let Ok(done) = tokio::time::timeout(Duration::from_secs(30), watch).await {
done?;
}
let closed = client.positions().close(&account, "BTC-USD", &ClosePosition::default()).await?;
println!("closed: {}", closed.status);
Ok(())
}<?php
require 'vendor/autoload.php';
use PhoenixPerps\Client;
$client = new Client();
if ($client->environment === 'live' && getenv('PHOENIXPERPS_ALLOW_LIVE') !== 'yes') {
fwrite(STDERR, "This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).\n");
exit(1);
}
$account = $client->accounts->list()->data[0]->id;
$btc = $client->markets->get('BTC-USD');
$order = $client->orders->create($account, [
'market' => 'BTC-USD',
'side' => 'buy',
'type' => 'market',
'size' => $btc->minSize,
'exits' => [
'stop_loss' => [
'percent' => '1',
'trail' => ['percent' => '0.5'],
'break_even' => ['trigger_percent' => '0.5', 'offset_ticks' => 2],
],
],
]);
printf("bought %s BTC (%s); watching the stop for 30 s\n", $order->size, $order->status);
for ($i = 0; $i < 6; $i++) {
sleep(5);
foreach ($client->exits->get($account, 'BTC-USD')->stopLoss ?? [] as $sl) {
printf("%s stop loss at %s (%s)\n", date('H:i:s'), $sl->price ?? '-', $sl->status);
}
}
$closed = $client->positions->close($account, 'BTC-USD', []);
printf("closed: %s\n", $closed->status);